day-4 javaScript

day-4 javaScript



What are Conditional Statements?


felse if, and else switch statement

if (true) { console.log('This message will print!'); }

let sale = true;
if(sale){
  console.log('Time to buy!');
}


if (false) { console.log('The code in this block will not run.'); } else { console.log('But the code in this block will!'); }

Comparison Operators

  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is equal to: ===
  • Is not equal to: !==







Logical Operators

Working with conditionals means that we will be using booleans, true or false values.



There are three logical operators:
  • the and operator (&&)
  • the or operator (||)
  • the not operator, otherwise known as the bang operator (!)
When we use the && operator, we are checking that two things are true:
if (stopLight === 'green' && pedestrians === 0) { console.log('Go!'); } else { console.log('Stop'); }


let mood = 'sleepy';
let tirednessLevel = 6;

if (mood === 'sleepy' && tirednessLevel > 8) {
  console.log('time to sleep');
else {
  console.log('not bed time yet');
}





Truthy and Falsy

  • 0
  • Empty strings like "" or ''
  • null which represent when there is no value at all
  • undefined which represent when a declared variable lacks a value
  • NaN, or Not a Number

Truthy and Falsy Assignment

the user does not have an account, making the username variable falsy. The code below checks if username is defined and assigns a default string if it is not:
let defaultName; if (username) { defaultName = username; } else { defaultName = 'Stranger'; }

 you combine your knowledge of logical operators you can use a short-hand for the code above. In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment:


let defaultName = username || 'Stranger';
Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.





Comments

Popular Posts