1. Variables
Variables are the fundamental building blocks for storing data in JavaScript. They can be declared using var
, let
, or const
.
Declaration and Initialization
-
var
: Function-scoped or globally-scoped. Example:
var age = 30;
-
let
: Block-scoped, recommended for mutable variables. Example:
let name = 'Alice';
-
const
: Block-scoped, immutable variable once assigned. Example:
const pi = 3.14;
- mutable object can be changed after it's created, and an immutable object can't.
- Mutable instance is passed by reference.
- Immutable instance is passed by value.
Hoisting
- Variables declared with
var
are hoisted to the top but not initialized. Example:
console.log(hoistedVar); // undefined
var hoistedVar = 'I am hoisted';
2. Math
JavaScript supports basic arithmetic operations and complex mathematical functions.
Basic Operators
- Addition (
+
), Subtraction (-
), Multiplication (*
), Division (/
). Example:
let sum = 10 + 5; // 15
let product = 10 * 5; // 50
Math Object
- Provides advanced mathematical functions. Example:
let maxVal = Math.max(10, 20, 30); // 30
let randomNum = Math.random(); // A random number between 0 and 1
3. Text
Strings in JavaScript are used for storing and manipulating text.
String Methods
-
length
: Returns the length of the string. Example:
let str = "Hello, World!";
console.log(str.length); // 13
-
toUpperCase()
,toLowerCase()
: Change case. Example:
console.log(str.toUpperCase()); // "HELLO, WORLD!"
-
substring()
: Extracts a part of the string. Example:
console.log(str.substring(0, 5)); // "Hello"
4. Arrays
Arrays are used to store multiple values in a single variable.
Creating Arrays
- Use square brackets
[]
. Example:
let fruits = ['Apple', 'Banana', 'Cherry'];
Array Methods
-
push()
,pop()
: Add/remove items from the end. Example:
fruits.push('Orange'); // ['Apple', 'Banana', 'Cherry', 'Orange']
fruits.pop(); // ['Apple', 'Banana', 'Cherry']
-
shift()
,unshift()
: Add/remove items from the beginning. Example:
fruits.shift(); // ['Banana', 'Cherry']
fruits.unshift('Strawberry'); // ['Strawberry', 'Banana', 'Cherry']
-
map()
,filter()
: Transform and filter arrays. Example:
let lengths = fruits.map(fruit => fruit.length); // [10, 6]
let shortFruits = fruits.filter(fruit => fruit.length < 7); // ['Banana']
5. Conditionals
Control the flow of your code with conditional statements.
if, else if, else
- Execute code based on conditions. Example:
let num = 10;
if (num > 10) {
console.log("Greater than 10");
} else if (num < 10) {
console.log("Less than 10");
} else {
console.log("Equal to 10");
}
switch
- Use for multiple conditions based on a single variable. Example:
let fruit = 'Apple';
switch (fruit) {
case 'Banana':
console.log('Banana is yellow');
break;
case 'Apple':
console.log('Apple is red');
break;
default:
console.log('Unknown fruit');
}
6. Loops
Loops allow repetitive tasks to be performed efficiently.
for Loop
- Iterates a specified number of times. Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
while Loop
- Iterates while a condition is true. Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
forEach
- Iterates over array elements. Example:
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));
7. Functions
Functions are reusable blocks of code designed to perform a particular task.
Function Declaration
- Define a function using
function
keyword. Example:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // "Hello, Alice!"
Function Expression
- Assign a function to a variable. Example:
const square = function(num) {
return num * num;
};
console.log(square(4)); // 16
Arrow Functions
- A shorter syntax for function expressions. Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
8. JavaScript Object Basics
Objects store collections of key-value pairs.
Creating Objects
- Use object literals
{}
. Example:
let person = {
name: 'John',
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet()); // "Hello, my name is John"
Accessing Properties
- Use dot notation or bracket notation. Example:
console.log(person.name); // "John"
console.log(person['age']); // 30
Adding/Modifying Properties
- Directly add or modify properties. Example:
person.job = 'Developer';
person.age = 31;
9. DOM Scripting
DOM (Document Object Model) scripting allows you to interact with and manipulate HTML and CSS.
Selecting Elements
- Use methods like
getElementById()
,querySelector()
. Example:
let heading = document.getElementById('main-heading');
let paragraphs = document.querySelectorAll('p');
Manipulating Elements
- Change content and style. Example:
heading.textContent = 'New Heading';
heading.style.color = 'blue';
10. Events
Events allow JavaScript to interact with user actions.
Event Listeners
- Attach event handlers to elements. Example:
let button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Button clicked!');
});
Common Events
-
click
,mouseover
,mouseout
,keydown
,load
. Example:
document.addEventListener('keydown', function(event) {
console.log(`Key pressed: ${event.key}`);
});
11. Async JavaScript Basics
Asynchronous programming allows your code to run without blocking other operations.
Callbacks
- Functions passed as arguments to be executed later. Example:
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched');
}, 2000);
}
fetchData(message => {
console.log(message);
});
Promises
- Represent eventual completion (or failure) of an asynchronous operation. Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve('Operation succeeded');
} else {
reject('Operation failed');
}
});
promise.then(message => {
console.log(message);
}).catch(error => {
console.error(error);
});
Async/Await
- Syntactic sugar for promises, making asynchronous code look synchronous. Example:
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchData();
12. Network Requests with fetch()
The fetch()
API allows you to make network requests similar to XMLHttpRequest
.
Making a Request
- Fetch data from a server. Example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error
:', error));
Handling Responses
- Convert response to usable data. Example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
13. Working with JSON
JSON (JavaScript Object Notation) is a common data format used for exchanging data.
Parsing JSON
- Convert JSON strings to JavaScript objects. Example:
let jsonString = '{"name": "John", "age": 30}';
let user = JSON.parse(jsonString);
console.log(user.name); // "John"
Stringifying Objects
- Convert JavaScript objects to JSON strings. Example:
let userObj = { name: 'Alice', age: 25 };
let userJSON = JSON.stringify(userObj);
console.log(userJSON); // '{"name":"Alice","age":25}'
14. Libraries and Frameworks
JavaScript libraries and frameworks can simplify development and add powerful features.
jQuery
- Simplifies DOM manipulation, event handling, and Ajax. Example:
$(document).ready(function() {
$('button').click(function() {
alert('Button clicked!');
});
});
React
- A library for building user interfaces. Example:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return <h1>Hello, World!</h1>;
}
ReactDOM.render(<App />, document.getElementById('root'));
Angular
- A framework for building web applications. Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>Hello, World!</h1>'
})
export class AppComponent {}
15. Debugging JavaScript
Debugging is essential for finding and fixing errors in your code.
Console Logging
- Use
console.log()
to inspect values. Example:
let value = 42;
console.log(value);
Debugger Statement
- Pause execution for debugging. Example:
function test() {
let x = 10;
debugger; // Pauses here
x += 5;
return x;
}
test();
Browser Developer Tools
- Use tools in browsers like Chrome and Firefox to inspect, debug, and profile your code.
Example:
- Open Developer Tools with F12 or right-click and select "Inspect". Use the "Console" tab to log messages and the "Sources" tab to set breakpoints and step through code.
Conclusion
Mastering JavaScript fundamentals equips you with the skills needed to build dynamic, interactive web applications. By understanding variables, math operations, text manipulation, arrays, conditionals, loops, functions, objects, DOM scripting, events, asynchronous programming, network requests, JSON, libraries and frameworks, and debugging techniques, you can create robust and efficient JavaScript applications. Dive into these core concepts to enhance your coding prowess and develop powerful web experiences.