[Go to site: main page, start]

0% found this document useful (0 votes)
5 views7 pages

JavaScript Basics: Code Examples Guide

The document provides JavaScript code examples covering variables, data types, functions, control flow, DOM manipulation, promises, async/await, array methods, and classes. Key notes emphasize best practices such as using 'const' and 'let', preferring arrow functions, and leveraging modern ES6+ features. It serves as a comprehensive guide for understanding and utilizing fundamental JavaScript concepts.

Uploaded by

shabana chotu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

JavaScript Basics: Code Examples Guide

The document provides JavaScript code examples covering variables, data types, functions, control flow, DOM manipulation, promises, async/await, array methods, and classes. Key notes emphasize best practices such as using 'const' and 'let', preferring arrow functions, and leveraging modern ES6+ features. It serves as a comprehensive guide for understanding and utilizing fundamental JavaScript concepts.

Uploaded by

shabana chotu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Code Examples

// ====================

// VARIABLES & DATA TYPES


// ====================

// Variable declaration
const name = "John"; // string
let age = 30; // number
var isStudent = false; // boolean
let score = null; // null
let undefinedVar; // undefined

// Object
const person = {
firstName: "Jane",
lastName: "Doe",
age: 28
};

// Array
const colors = ["red", "green", "blue"];

// ====================

// FUNCTIONS
// ====================

// Basic function
function greet(name) {

return `Hello, ${name}! `;


}

// Arrow function (ES6)


const addNumbers = (a, b) => a + b;

// Callback function
function processUserInput(callback) {
const name = prompt("Please enter your name:");
callback(name);
}

// ====================

// CONTROL FLOW
// ====================

// If-else statement
if (age >= 18) {

[Link]("You are an adult ");


} else {

[Link]("You are a minor ");


}
// Switch statement
switch (new Date().getDay()) {
case 0:

[Link]("Sunday ");
break;
case 6:

[Link]("Saturday ");
break;
default:

[Link]("Weekday ");
}

// For loop
for (let i = 0; i < 5; i++) {

[Link](`Iteration ${i} `);


}

// ====================

// DOM MANIPULATION
// ====================

// Select element
const button = [Link]("#myButton");

// Event listener
[Link]("click", () => {

[Link]("Button clicked! ");


[Link] = "lightblue";
});

// Create element
const newDiv = [Link]("div");

[Link] = "New element created! ";


[Link](newDiv);

// ====================

// PROMISES & ASYNC/AWAIT


// ====================

// Promise example
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // simulate success/failure
if (success) {

resolve("Data fetched successfully! ");


} else {

reject("Error fetching data! ");


}
}, 2000);
});
// Async/await example
async function getUserData() {
try {
const response = await fetch('[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error:", error);
}
}

// ====================

// ARRAY METHODS
// ====================

const numbers = [1, 2, 3, 4, 5];

// map()
const doubled = [Link](num => num * 2);

// filter()
const evens = [Link](num => num % 2 === 0);

// reduce()
const sum = [Link]((total, num) => total + num, 0);
// forEach()
[Link](num => [Link](num));

// ====================

// CLASSES (ES6)
// ====================

class Animal {
constructor(name) {
[Link] = name;
}

speak() {

[Link](`${[Link]} makes a noise. `);


}
}

class Dog extends Animal {


speak() {

[Link](`${[Link]} barks. `);


}
}

const myDog = new Dog("Rex");


[Link]();

Key Notes
1. Variables: Use const by default, let when reassignment is needed,
and avoid var
2. Functions: Prefer arrow functions for concise syntax and
proper this binding
3. Async Code: Use promises or async/await for cleaner asynchronous
code
4. DOM: Remember to wait for DOM content to load before
manipulating elements
5. ES6+: Modern JavaScript has many helpful features like classes,
template literals, destructuring, etc.

You might also like