Incredible Examples That Will Blow Your Mind,
Impressive JavaScript
Examples to Elevate Your Skills!
Formula of a High-Speed JavaScript Engine
In JavaScript, variables are containers that store data values. These values can have different types, depending on the type of data they represent. Here are some common data types in JavaScript:
Numbers:
Used to represent numeric values, both integers (whole numbers) and floating-point numbers (numbers with decimal points).
Code:
let age = 30; let pi = 3.14;
Strings:
Used to represent sequences of characters, enclosed in single ('') or double ("") quotes.
Code:
let name = "John"; let message = 'Hello, world!';
Booleans:
Used to represent true or false values, indicating the logical state of a condition.
Code:
let isLogged = true; let hasPermission = false;
Arrays:
Used to store multiple values in a single variable. Arrays are ordered collections and can contain elements of different data types.
Code:
let numbers = [1, 2, 3, 4, 5]; let fruits = ["apple", "banana", "orange"];
Objects:
Used to store data in key-value pairs, where keys are strings (also called properties) and values can be of any data type.
Code:
let person = { name: "John", age: 30, isEmployed: true };
JavaScript is a dynamically-typed language, meaning you don't need to explicitly declare the data type of a variable. It will automatically determine the type based on the assigned value. For example, if you assign a number to a variable, it becomes a number type; if you assign a string, it becomes a string type, and so on.
Code:
let x = 10; // x is now a number x = "hello"; // x is now a string x = true; // x is now a boolean
Variables:
Variables are used to store data in JavaScript. You can declare variables using the `var`, `let`, or `const` keywords. `let` and `const` was introduced in ECMAScript 6 (ES6) and are preferable for most use cases.
Code:
// Declaring variables let age = 25; const name = "John"; // Reassigning variables age = 26;
Data Types:
JavaScript has various data types, including numbers, strings, booleans, objects, arrays, functions, null, and undefined.
Code:
let num = 42; // Number let message = "Hello, World!"; // String let isTrue = true; // Boolean let person = { name: "Alice", age: 30 }; // Object let fruits = ["apple", "banana", "orange"]; // Array let greet = function() { console.log("Hi!"); }; // Function let emptyValue = null; // Null let notDefined; // Undefined
Functions:
Functions are blocks of reusable code that perform specific tasks when called. They can take parameters and return values.
Code:
function add(a, b) { return a + b; } const result = add(3, 5); // Calling the function console.log(result); // Output: 8
Control Flow:
Control flow involves decision-making structures like if-else statements and loops (for, while) to control the flow of a program based on certain conditions.
Code:
let num = 10; if (num > 0) { console.log("Positive"); } else if (num < 0) { console.log("Negative"); } else { console.log("Zero"); } // Output: Positive
Objects:
Objects are key-value pairs used to group related data and functions together.
Code:
const person = { name: "Alice", age: 30, greet: function() { console.log("Hello, my name is " + this.name); } }; console.log(person.name); // Output: Alice person.greet(); // Output: Hello, my name is Alice
Arrays:
Arrays are collections of elements that can be of any data type.
Code:
const fruits = ["apple", "banana", "orange"]; console.log(fruits[1]); // Output: banana fruits.push("grape"); // Adding an element to the end of the array console.log(fruits); // Output: ["apple", "banana", "orange", "grape"] fruits.pop(); // Removing the last element from the array console.log(fruits); // Output: ["apple", "banana", "orange"]
Scope:
Scope determines the accessibility and lifetime of variables in JavaScript.
Code:
function greet() { const message = "Hello"; console.log(message); } greet(); // Output: Hello console.log(message); // Error: 'message' is not defined (out of scope)
Closures:
Closures occur when a function remembers the variables outside of it, even after the outer function has finished executing.
Code:
function outer() { const outerVar = "I'm from the outer function"; function inner() { console.log(outerVar); } return inner; } const closureExample = outer(); closureExample(); // Output: I'm from the outer function
Asynchronous JavaScript:
JavaScript is single-threaded, but it can handle asynchronous tasks using callbacks, Promises, and async/await.
Code:
function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { const data = "Some fetched data"; resolve(data); }, 2000); }); } fetchData().then((data) => { console.log(data); // Output after 2 seconds: Some fetched data });
Prototypes and Classes:
JavaScript uses prototypes to create objects and share behavior between them. ES6 introduced the class syntax for a more familiar approach to object-oriented programming.
Example with Classes:
Code:
class Animal { constructor(name) { this.name = name; } makeSound() { console.log("Some generic sound"); } } class Dog extends Animal { constructor(name) { super(name); } makeSound() { console.log("Woof!"); } } const dog = new Dog("Buddy"); dog.makeSound(); // Output: Woof!
For Loop:
The for loop is commonly used when you know the number of iterations beforehand.
Example: Printing numbers from 1 to 5 using a for loop.
Code:
for (let i = 1; i <= 5; i++) { console.log(i); }
While Loop:
The while loop is used when the number of iterations is not known beforehand, and it continues executing the code block as long as the specified condition is true.
Example: Printing numbers from 1 to 5 using a while loop.
Code:
let i = 1; while (i <= 5) { console.log(i); i++; }
Do-While Loop:
The do-while loop is similar to the while loop, but it ensures that the code block is executed at least once before checking the condition.
Example: Printing numbers from 1 to 5 using a do-while loop.
Code:
let i = 1; do { console.log(i); i++; } while (i <= 5);
The Secret Formula of a High-Speed JavaScript Engine
Code:
function calculateFactorial(n) { if (n <= 1) return 1; return n * calculateFactorial(n - 1); } console.log(calculateFactorial(5)); // Output: 120
Code:
const fruits = ['apple', 'banana', 'orange']; for (const fruit of fruits) { console.log(fruit); }
Code:
const greet = name => `Hello, ${name}!`; console.log(greet('Alice')); // Output: Hello, Alice!
Code:
const nums = [2, 4, 6]; const doubled = nums.map(num => num * 2); console.log(doubled); // Output: [4, 8, 12]
Code:
const sum = (a, b) => a + b; console.log(sum(3, 5)); // Output: 8
Code:
const button = document.getElementById('myButton'); button.addEventListener('click', () => { console.log('Button clicked!'); });