Conditional Statements
- Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this. -
In JavaScript we have the following conditional statements:
- Use
ifto specify a block of code to be executed, if a specified condition is true - Use
elseto specify a block of code to be executed, if the same condition is false - Use
else ifto specify a new condition to test, if the first condition is false - Use
switchto specify many alternative blocks of code to be executed
- Use
-
if Statement
- Use the
ifstatement to specify a block of JavaScript code to be executed if a condition is true. -
Syntax :
if (condition) { // block of code to be executed if the condition is true } - Note that
ifis in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. -
EX :
if (hour < 18) { greeting = "Good day"; }
- Use the
-
The else Statement
- Use the
elsestatement to specify a block of code to be executed if the condition is false. -
Syntax :
if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } -
EX :
if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
- Use the
-
else if Statement
- Use the
else ifstatement to specify a new condition if the first condition is false. -
Syntax :
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } -
EX :
if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
- Use the
Switch Statement
- Use the
switchstatement to select one of many code blocks to be executed. -
EX :
switch(expression) { case x: // code block break; case y: // code block break; default: // code block } -
This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
-
EX :
Theswitch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; }getDay()method returns the weekday as a number between 0 and 6. -
The break Keyword
- When JavaScript reaches a
breakkeyword, it breaks out of the switch block. - This will stop the execution inside the switch block.
- It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
- If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
- When JavaScript reaches a
-
The default Keyword
- The
defaultkeyword specifies the code to run if there is no case match. -
EX :
switch (new Date().getDay()) { case 6: text = "Today is Saturday"; break; case 0: text = "Today is Sunday"; break; default: text = "Looking forward to the Weekend"; } - The
defaultcase does not have to be the last case in a switch block - If
defaultis not the last case in the switch block, remember to end the default case with a break.
- The
-
Common Code Blocks
- Sometimes you will want different switch cases to use the same code.
-
EX :
In this example case 4 and 5 share the same code block, and 0 and 6 share another code block.switch (new Date().getDay()) { case 4: case 5: text = "Soon it is Weekend"; break; case 0: case 6: text = "It is Weekend"; break; default: text = "Looking forward to the Weekend"; }
-
Switching Details
- If multiple cases matches a case value, the first case is selected.
- If no matching cases are found, the program continues to the
defaultlabel. - If no default label is found, the program continues to the statement(s)
after the switch.
-
Strict Comparison
- The values must be of the same type to match.
- A strict comparison can only be true if the operands are of the same type.
-
EX :
let x = "0"; switch (x) { case 0: text = "Off"; break; case 1: text = "On"; break; default: text = "No value found"; }
Conditional (Ternary) Operator
- JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
- Syntax :
variablename = (condition) ? value1:value2 - EX :
let voteable = (age < 18) ? "Too young":"Old enough"; - If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough".
try and catch
- The
trystatement allows you to define a block of code to be tested for errors while it is being executed. - The
catchstatement allows you to define a block of code to be executed, if an error occurs in the try block. -
The JavaScript statements try and catch come in pairs:
try { Block of code to try } catch(err) { Block of code to handle errors } -
throw Statement
- The
throwstatement allows you to create a custom error. - Technically you can throw an exception (throw an error).
- The exception can be a JavaScript String, a Number, a Boolean or an Object.
- If you use throw together with try and catch, you can control program flow and generate custom error messages.
- The
-
EX:
Please input a number between 5 and 10:
-
finally Statement
- The
finallystatement lets you execute code, after try and catch, regardless of the result. -
Syntax :
try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result } -
EX:
JavaScript try catch
Please input a number between 5 and 10:
- The
JS Function Definitions
- JavaScript functions are defined with the function keyword.
- You can use a function declaration or a function expression.
-
Function Declarations
- Syntax :
function functionName(parameters) { // code to be executed } - Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).
-
EX:
This example calls a function which performs a calculation 3*4:
- Syntax :
-
Function Expressions
- A JavaScript function can also be defined using an expression.
- A function expression can be stored in a variable.
-
EX:
const x = function (a, b) {return a * b}; let z = x(4, 3); - The function above is actually an anonymous function (a function without a name).
- The function above ends with a semicolon because it is a part of an executable statement.
-
The Function() Constructor
- As you have seen in the previous examples, JavaScript functions are defined with the
functionkeyword. - Functions can also be defined with a built-in JavaScript function constructor called
Function(). -
EX:
You actually don't have to use the function constructor. The example above is the same as writing.const myFunction = new Function("a", "b", "return a * b"); let x = myFunction(4, 3);const myFunction = function (a, b) {return a * b}; let x = myFunction(4, 3); -
Self-Invoking Functions
- Function expressions can be made "self-invoking".
- A self-invoking expression is invoked (started) automatically, without being called.
- Function expressions will execute automatically if the expression is followed by ().
- You cannot self-invoke a function declaration.You have to add parentheses around the function to indicate that it is a function expression.
-
EX:
(function () { let x = "Hello!!"; // I will invoke myself })(); - The function above is actually an anonymous self-invoking function (function without name).
- As you have seen in the previous examples, JavaScript functions are defined with the
-
Functions are Objects
- JavaScript functions have both properties and methods.
- The
arguments.lengthproperty returns the number of arguments received when the function was invoked. -
EX:
function myFunction(a, b) { return arguments.length; } - The
toString()method returns the function as a string. -
EX:
function myFunction(a, b) { return a * b; } let text = myFunction.toString();
-
Function Parameters and Arguments
- Function parameters are the names listed in the function definition.
- Function arguments are the real values passed to (and received by) the function.
-
Parameter Rules
- JavaScript function definitions do not specify data types for parameters.
- JavaScript functions do not perform type checking on the passed arguments.
- JavaScript functions do not check the number of arguments received.
-
Default Parameters
- If a function is called with missing arguments (less than declared), the missing values are set to
undefined. - Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter.
-
EX:
Setting a default value to a function parameter.
- If a function is called with missing arguments (less than declared), the missing values are set to
-
Arguments Object
- JavaScript functions have a built-in object called the arguments object.
- The argument object contains an array of the arguments used when the function was called (invoked).
- This way you can simply use a function to find (for instance) the highest value in a list of numbers.
-
Finding the largest number:
Finding the largest number.
-
Sum of all arguments:
Sum of all arguments:
-
JavaScript Function Invocation
- The code inside a function is executed when the function is invoked.
- It is common to use the term "call a function" instead of "invoke a function".
-
this Keyword
- In JavaScript, the thing called
this, is the object that "owns" the current code. - The value of
this, when used in a function, is the object that "owns" the function. - Note that
thisis not a variable. It is a keyword. You cannot change the value ofthis. -
EX:
const myObject = { firstName:"Ahmed", lastName: "Mohamed", fullName: function () { return this.firstName + " " + this.lastName; } } myObject.fullName();
- In JavaScript, the thing called
JavaScript For Loop
JavaScript supports different kinds of loops:
for- loops through a block of code a number of timesfor/in- loops through the properties of an objectfor/of- loops through the values of an iterable objectwhile- loops through a block of code while a specified condition is truedo/while- also loops through a block of code while a specified condition is true
-
For Loop
-
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) { // code block to be executed } -
Statement 1 is executed (one time) before the execution of the code block.
- Normally you will use statement 1 to initialize the variable used in the loop (let i = 0).
- This is not always the case, JavaScript doesn't care. Statement 1 is optional.
-
You can initiate many values in statement 1 (separated by comma):
for (let i = 0, len = cars.length, text = ""; i < len; i++) { text += cars[i] + <br>; } -
And you can omit statement 1 (like when your values are set before the loop starts):
let i = 2; let len = cars.length; let text = ""; for (; i < len; i++) { text += cars[i] + <br>; }
-
Statement 2 defines the condition for executing the code block.
- Often statement 2 is used to evaluate the condition of the initial variable.
- This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
- If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
- If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.
-
Statement 3 is executed (every time) after the code block has been executed.
- Often statement 3 increments the value of the initial variable.
- This is not always the case, JavaScript doesn't care, and statement 3 is optional.
- Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
-
Statement 3 can also be omitted (like when you increment your values inside the loop):
let i = 0; let len = cars.length; let text = ""; for (; i < len; ) { text += cars[i] + <br>; i++; }
-
Loop Scope
-
Using var in a loop:
using var, the variable declared in the loop redeclares the variable outside the loop.
var i = 5; for (var i = 0; i < 10; i++) { // some statements } document.getElementById("demo").innerHTML = i; -
Using let in a loop:
using let, the variable declared in the loop does not redeclare the variable outside the loop.
When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.let i = 5; for (let i = 0; i < 10; i++) { // some statements } document.getElementById("demo").innerHTML = i;
-
-
The for loop has the following syntax:
-
For In Loop
- The JavaScript
for instatement loops through the properties of an Object -
Syntax :
for (key in object) { // code block to be executed } -
EX :
const person = {fname:"John", lname:"Doe", age:25}; let txt = ""; for (let x in person) { txt += person[x] + <br>; } document.getElementById("demo").innerHTML = txt; -
For In Over Arrays
- The JavaScript
for instatement can also loop over the properties of an Array. -
Syntax :
for (variable in array) { // code block to be executed } -
EX :
const numbers = [45, 4, 9, 16, 25]; let txt = ""; for (let x in numbers) { txt += numbers[x]; } document.getElementById("demo").innerHTML = txt; - Do not use for in over an Array if the index order is important.
- The index order is implementation-dependent, and array values may not be accessed in the order you expect.
- It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.
- The JavaScript
-
Array.forEach()
- The
forEach()method calls a function (a callback function) once for each array element. -
EX:
JavaScript Array.forEach()
Calls a function once for each array element.
- The
- The JavaScript
-
For Of Loop
- The JavaScript
for ofstatement loops through the values of an iterable object. - It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.
-
Syntax :
for (variable of iterable) { // code block to be executed } - variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
- iterable - An object that has iterable properties.
-
Examples
Looping over an Array
const cars = ["BMW", "Volvo", "Mini"]; let text = ""; for (let x of cars) { text += x; }Looping over a String
let language = "JavaScript"; let text = ""; for (let x of language) { text += x; }
- The JavaScript
-
While Loop
- The
whileloop loops through a block of code as long as a specified condition is true. -
Syntax :
while (condition) { // code block to be executed } -
EX: In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:
while (i < 10) { text += "The number is " + i; i++; } - If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
- The
-
Do While Loop
- The
do whileloop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. -
Syntax:
do { // code block to be executed } while (condition); -
EX: The example below uses a
do whileloop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:do { text += "The number is " + i; i++; } while (i < 10); - Do not forget to increase the variable used in the condition, otherwise the loop will never end!
- The
-
Break and Continue
- The
breakstatement "jumps out" of a loop. -
the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3.for (let i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + <br>; } - The
continuestatement "jumps over" one iteration in the loop. -
This example skips the value of 3for (let i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; }
- The
-
JavaScript Labels
-
To label JavaScript statements you precede the statements with a label name and a colon:
The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.label: statements
Syntax:
break labelname; continue labelname; -
EX:
JavaScript break
-
To label JavaScript statements you precede the statements with a label name and a colon: