If statement
Basic If Statement
An if statement executes a block of code if the specified condition evaluates to true.
Syntax
if (condition) {
// code to execute if condition is true
}
Example
if (answer === 42) {
console.log('Told you so!');
}
ELSE
An else statement executes a block of code if the condition in the if statement evaluates to false.
Syntax
if (condition) {
// block of code if condition is true
} else {
// block of code if condition is false
}
Example
if (animal == 'dog') {
console.log('Bark, bark!');
} else {
console.log('Meow!');
}
ELSE IF
An else if statement provides a new condition to test if the first condition is false.
Syntax
if (condition1) {
// block of code if condition1 is true
} else if (condition2) {
// block of code if condition2 is true
} else {
// block of code if both conditions are false
}
Example
if (someNumber > 10) {
console.log('Numbers larger than 10 are not allowed.');
} else if (someNumber < 0) {
console.log('Negative numbers are not allowed.');
} else {
console.log('Nice number!');
}
Loops
FOR LOOPS
A for loop repeats until a specified condition evaluates to false, commonly used for iterating over arrays or executing a block of code a predetermined number of times.
Syntax
for (initialization; condition; increment) {
// code block to be executed
}
Example
for (let i = 0; i < 5; i++) {
console.log(i); // Prints the numbers from 0 to 4
}
WHILE LOOPS
A while loop executes its statements as long as the specified condition evaluates to true.
Syntax
while (condition) {
// code block to be executed
}
Example
let x = 0;
while (x < 5) {
console.log(x); // Prints numbers from 0 to 4
x++;
}
DO WHILE LOOPS
A do…while loop executes its statements once before checking if the condition is true, then it repeats the loop as long as the condition is true.
Syntax
do {
// code block to be executed
} while (condition);
Example
let x = 0;
do {
console.log(x); // Prints numbers from 0 to 4
x++;
} while (x < 5);
Read more: do…while
Math
Basic Mathematical Operations
JavaScript provides a Math object which encapsulates a variety of mathematical functions and constants.
// Generate a random number between 0 (inclusive) and 1 (exclusive)
Math.random();
// Round a number downward to its nearest whole number
Math.floor(4.7); // 4
// Calculate the power of a number
Math.pow(4, 2); // 16
Each method serves specific mathematical operations, ranging from basic arithmetic to complex calculations. Refer to the Mozilla Math Reference for a comprehensive understanding and additional examples.
Numbers
Basic Arithmetic
JavaScript supports standard arithmetic operations such as addition, subtraction, multiplication, and division.
// Addition
console.log(5 + 2); // 7
// Subtraction
console.log(5 - 2); // 3
// Multiplication
console.log(5 * 2); // 10
// Division
console.log(10 / 2); // 5
Special Number Operations
Beyond basic arithmetic, JavaScript Numbers can handle modulus, incrementation, decrementation, and detect non-numeric values.
// Modulus (Remainder)
console.log(10 % 4); // 2
// Increment
let x = 5;
console.log(++x); // 6
// Decrement
let y = 5;
console.log(--y); // 4
// Checking if a value is NaN (Not-a-Number)
console.log(isNaN("Hello")); // true
Objects
Creating and Accessing Objects
Objects in JavaScript can be created using object literals, and their properties can be accessed using dot notation or bracket notation.
// Creating an object
let person = {
name: "John",
age: 30
};
// Accessing object properties
console.log(person.name); // John
console.log(person['age']); // 30
Popup Boxes
Alert, Confirm, and Prompt
JavaScript provides three types of popup boxes: alert, confirm, and prompt, each serving different purposes.
// Alert box
alert("This is an alert box!");
// Confirm box
if (confirm("Are you sure?")) {
console.log("Confirmed.");
} else {
console.log("Canceled.");
}
// Prompt box
let userResponse = prompt("Please enter your name:", "");
console.log(userResponse);
Strings
Basic String Operations
Strings in JavaScript are used to represent and manipulate a sequence of characters.
// Concatenation
let hello = "Hello, ";
let world = "world!";
console.log(hello + world); // "Hello, world!"
// Finding the length of a string
let str = "Hello, world!";
console.log(str.length); // 13
// Accessing characters in a string
console.log(str.charAt(0)); // "H"
Switch Statements
Using Switch for Conditional Logic
Switch statements are a way to execute different parts of code based on different cases.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Bananas are yellow.");
break;
case "apple":
console.log("Apples are delicious.");
break;
default:
console.log("Unknown fruit.");
break;
}
Ternary Operator
Conditional (Ternary) Operator
The ternary operator is a shortcut for the if-else statement that is used to assign values based on a condition.
// Syntax
condition ? valueIfTrue : valueIfFalse;
// Example
let age = 19;
let canVote = age >= 18 ? "Yes, you can vote." : "No, you cannot vote.";
console.log(canVote); // "Yes, you can vote."
Variables
Declaring Variables
Variables can be declared in JavaScript using var
, let
, or const
, each with different scopes and mutability characteristics.
// var
var name = "John Doe";
// let
let age = 30;
// const
const birthday = "January 1, 1990";
Scope and Hoisting
Understanding the scope and hoisting behavior of variables is crucial in JavaScript development.
// Scope
if (true) {
var varVariable = "This is var";
let letVariable = "This is let";
}
console.log(varVariable); // Accessible
// console.log(letVariable); // Uncaught ReferenceError: letVariable is not defined
// Hoisting
console.log(hoistedVar); // undefined
var hoistedVar = "Hoisted";
Additional JavaScript Concepts
Event Handling
JavaScript allows interactive web pages by responding to user events.
// Example: Click event
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
Asynchronous JavaScript
JavaScript supports asynchronous programming patterns like callbacks, promises, and async/await for non-blocking operations.
// Promise example
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Modules
JavaScript modules allow you to split your code into separate files, making it more maintainable and reusable.
// Exporting a module
export const myFunction = () => {
console.log("Hello, module!");
};
// Importing a module
import { myFunction } from './myModule.js';
myFunction(); // "Hello, module!"
For comprehensive details on JavaScript, including advanced topics and best practices, consider visiting the MDN Web Docs.
Error Handling
Try, Catch, Finally
Error handling in JavaScript is accomplished using try
, catch
, finally
blocks. This structure allows you to attempt to execute code that may throw an error, catch that error, and finally execute code regardless of the result.
// Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to execute if an error occurs
} finally {
// Code that executes after try/catch, regardless of outcome
}
// Example
try {
console.log(nonExistentVariable); // This will throw an error
} catch (error) {
console.error("Caught an error:", error);
} finally {
console.log("This always executes.");
}
Debugging
Console Methods and Debuggers
Debugging is a critical skill for any developer. JavaScript provides console methods like console.log()
, console.error()
, and console.warn()
for logging information to the browser’s console. Additionally, the debugger
statement can be used to invoke any available debugging functionality, such as setting breakpoints.
// Using console
console.log("Log message");
console.error("Error message");
console.warn("Warning message");
// Using debugger
debugger; // Execution will pause here if the developer console is open
Good Practices
Coding Standards and Best Practices
Adhering to good practices in JavaScript enhances code readability, maintainability, and reduces the likelihood of errors.
- Use clear and meaningful variable names.
- Comment your code where necessary to explain “why” something is done.
- Keep functions focused on a single task.
- Avoid global variables to reduce the risk of conflicts.
- Use
let
and const
for variable declarations to ensure block-level scope.
- Handle errors gracefully using
try/catch
blocks.
- Write modular code using functions, classes, and modules.
- Follow consistent coding conventions regarding naming, syntax, and structure.
For an in-depth look into best practices, visit MDN Web Docs: JavaScript Guide.
Approx. read time: 8.5 min.
Post: JavaScript Glossary
JavaScript Glossary, for the beginner and new to JavaScript programmer
For a more comprehensive reference see Mozilla JavaScript Reference.
Arrays
ACCESSING ARRAY ELEMENTS
You can get elements out of arrays if you know their index. Array elements’ indices start at 0 and increment by 1, so the first element’s index is 0, the second element’s index is 1, the third element’s index is 2, etc.
Syntax
array[index];
Creating Array and Fetching Elements in JavaScript
ARRAY LITERALS
You can create arrays in two different ways. The most common of which is to list values in a pair of square brackets. JavaScript arrays can contain any types of values and they can be of mixed types.
Syntax
const arrayName = [element0, element1, ..., elementN]
Read more: Mozilla JavaScript Array Reference
Creating JavaScript Arrays with Array literals and spread operator
MULTI-DIMENSIONAL ARRAYS
A two-dimensional array is an array within an array. If you fill this array with another array you get a three-dimensional array and so on.
ARRAY CONSTRUCTOR
You can also create an array using the Array constructor.
Read more: Creating an array
ACCESSING NESTED ARRAY ELEMENTS
Accessing multi-dimensional array elements is quite similar to one-dimension arrays. They are accessed by using [index][index]….. (number of them depends upon the number of arrays deep you want to go inside).
Syntax
array[index][index] //...
Booleans
BOOLEAN LITERALS
Syntax
true
false
BOOLEAN LOGICAL OPERATORS
Console
CONSOLE.LOG
Prints text to the console. Useful for debugging.
CONSOLE.TIME
This function starts a timer which is useful for tracking how long an operation takes to happen.
Read more: console.time
CONSOLE.TIMEEND()
Stops a timer that was previously started by calling console.time().
Read more: console.timeEnd
Functions
Function Declaration
A function is a JavaScript procedure—a set of statements that performs a task or calculates a value.
Read more: Functions
FUNCTION CALLING
FUNCTION HOISTING
The two ways of declaring functions produce different results. Declaring a function one way “hoists” it to the top of the call, and makes it available before it’s actually defined.
Read more: Hoisting
If statement
Basic If Statement
An if statement executes a block of code if the specified condition evaluates to true.
ELSE
An else statement executes a block of code if the condition in the if statement evaluates to false.
ELSE IF
An else if statement provides a new condition to test if the first condition is false.
Loops
FOR LOOPS
A for loop repeats until a specified condition evaluates to false, commonly used for iterating over arrays or executing a block of code a predetermined number of times.
WHILE LOOPS
A while loop executes its statements as long as the specified condition evaluates to true.
DO WHILE LOOPS
A do…while loop executes its statements once before checking if the condition is true, then it repeats the loop as long as the condition is true.
Read more: do…while
Math
Basic Mathematical Operations
JavaScript provides a Math object which encapsulates a variety of mathematical functions and constants.
Each method serves specific mathematical operations, ranging from basic arithmetic to complex calculations. Refer to the Mozilla Math Reference for a comprehensive understanding and additional examples.
Numbers
Basic Arithmetic
JavaScript supports standard arithmetic operations such as addition, subtraction, multiplication, and division.
Special Number Operations
Beyond basic arithmetic, JavaScript Numbers can handle modulus, incrementation, decrementation, and detect non-numeric values.
Objects
Creating and Accessing Objects
Objects in JavaScript can be created using object literals, and their properties can be accessed using dot notation or bracket notation.
Popup Boxes
Alert, Confirm, and Prompt
JavaScript provides three types of popup boxes: alert, confirm, and prompt, each serving different purposes.
Strings
Basic String Operations
Strings in JavaScript are used to represent and manipulate a sequence of characters.
Switch Statements
Using Switch for Conditional Logic
Switch statements are a way to execute different parts of code based on different cases.
Ternary Operator
Conditional (Ternary) Operator
The ternary operator is a shortcut for the if-else statement that is used to assign values based on a condition.
Variables
Declaring Variables
Variables can be declared in JavaScript using
var
,let
, orconst
, each with different scopes and mutability characteristics.Scope and Hoisting
Understanding the scope and hoisting behavior of variables is crucial in JavaScript development.
Additional JavaScript Concepts
Event Handling
JavaScript allows interactive web pages by responding to user events.
Asynchronous JavaScript
JavaScript supports asynchronous programming patterns like callbacks, promises, and async/await for non-blocking operations.
Modules
JavaScript modules allow you to split your code into separate files, making it more maintainable and reusable.
For comprehensive details on JavaScript, including advanced topics and best practices, consider visiting the MDN Web Docs.
Error Handling
Try, Catch, Finally
Error handling in JavaScript is accomplished using
try
,catch
,finally
blocks. This structure allows you to attempt to execute code that may throw an error, catch that error, and finally execute code regardless of the result.Debugging
Console Methods and Debuggers
Debugging is a critical skill for any developer. JavaScript provides console methods like
console.log()
,console.error()
, andconsole.warn()
for logging information to the browser’s console. Additionally, thedebugger
statement can be used to invoke any available debugging functionality, such as setting breakpoints.Good Practices
Coding Standards and Best Practices
Adhering to good practices in JavaScript enhances code readability, maintainability, and reduces the likelihood of errors.
let
andconst
for variable declarations to ensure block-level scope.try/catch
blocks.For an in-depth look into best practices, visit MDN Web Docs: JavaScript Guide.
100+ JavaScript Concepts you Need to Know
Related Videos:
Related Posts:
What is Python?
What is the default value for Boolean variable in VB.NET?
Learn about JavaScript ELSE STATEMENTS
Learn about JavaScript IF STATEMENTS
Disable Search in WordPress
Related Posts
The Human Equation: Why Understanding People is the Key to Business Success
Comprehensive Economic and Zoning Simulation
Mastering Lottery Odds: A Step-by-Step Guide to Calculating Your Winning Probability
Understanding Financial Language: Q and KDB Databases
Silent Warfare: Unveiling the Secrets of State-Sponsored Malware and Cyber-Espionage
Game Crashing At The First Frame – Resolving Segmentation Faults in C++ Due to Bad File Descriptors
The Berry Seed of an Idea: Dreaming Up “Poons”
Directory Listing Batch Script
Revolutionizing Autonomy: Introducing a Next-Generation Algorithm for Autopilot Cars
Guiding AI Through Labyrinth: Right-Hand Wall Following Algorithm for Maze Navigation – Python
Optimizing Unity Editor Layout for Enhanced Game Development Workflow
Introduction to the Unity Editor
About the Author: Bernard Aybout (Virii8)