29.07.2016 Views

front-end-developer_1_

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Front-End-Developer - Level 1<br />

$(document).ready(function() {<br />

var age = parseInt(prompt("How old are you?"));<br />

if (age > 21) {<br />

$('#drinks').show();<br />

} else if (age === 21) {<br />

alert("Now don't go crazy!");<br />

$('#drinks').show();<br />

} else {<br />

$('#under-21').show();<br />

}<br />

});<br />

Notice the triple equals operator. When we're asking whether something is equal, we use<br />

=== (3 equal signs). When we're setting a variable equal to something, we use = . Mixing<br />

these up is one of the easiest syntax errors to make.<br />

JavaScript also has an operator with 2 equal signs, but it is almost never used, and you<br />

should generally avoid it. It does things like return true for "2" == 2 , but many of its rules<br />

are confusing, inconsistent, and hard to remember.<br />

When JavaScript tries to figure out if the condition is true, it's looking for a boolean.<br />

Remember booleans - true and false ? They were returned from the confirm() function.<br />

Check out what's going on here in the JavaScript console:<br />

var age = 22;<br />

age > 21;<br />

We're getting a boolean, just like with confirm() . We could write the JavaScript for our<br />

drinks page like this:<br />

scripts.js<br />

$(document).ready(function() {<br />

var over21 = confirm("Are you over 21? Click OK for yes or Cancel for no.");<br />

if (over21) {<br />

$('#drinks').show();<br />

} else {<br />

$('#under-21').show();<br />

}<br />

});<br />

Branching<br />

121

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!