If Else, the Date Object, & Creating Elements
Master JavaScript Conditionals and Dynamic Element Creation
Core JavaScript Concepts You'll Learn
Conditional Logic
Learn if-else statements to make your code execute only when specific criteria are met. Master the foundation of programming decision-making.
Date Object Manipulation
Harness JavaScript's Date object to retrieve current time information and create time-based functionality in your applications.
Dynamic Element Creation
Build HTML elements programmatically using JavaScript's createElement method to add interactive content to your web pages.
Conditional logic is essential for creating intelligent applications. Every programming language relies on if-else statements to make decisions based on different criteria.
Access the Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
You should observe the message: Item is in stock
Back in your code editor, modify the boolean value to false:
let inStock = false;
if(inStock == true) {
console.log('Item is in stock');
}Save and reload the page in Chrome.
The Console should now be empty—our condition evaluated to false, so no code executed.
Now add an else clause to handle the false condition:
let inStock = false;
if(inStock == true) {
console.log('Item is in stock');
}
else {
console.log('Item is out of stock');
}Save and reload the page in Chrome.
The Console should now display: Item is out of stock
Assignment vs Comparison Operators
| Feature | Single = (Assignment) | Double == (Comparison) |
|---|---|---|
| Purpose | Sets a value | Tests/compares values |
| Example | X = 8 | X == 8 |
| Result | Variable is changed | Returns true or false |
| Use Case | Variable declaration | Conditional statements |
The 'new' keyword creates an instance of the Date object using the constructor method. This pattern gives you access to all Date object methods and properties.
Essential Date Object Methods
getHours()
Returns the current hour in 24-hour military format. 4 PM appears as 16, making it perfect for time-based conditionals.
getMonth()
Retrieves the current month as a number. Remember that months are zero-indexed, so January is 0 and December is 11.
getFullYear()
Returns the complete four-digit year. Use this instead of getYear() which returns a two-digit year that can cause confusion.
Conditional logic is essential for creating intelligent applications. Every programming language relies on if-else statements to make decisions based on different criteria.
Key Takeaways
