Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Java Script

The document is a comprehensive JavaScript cheat sheet covering its structure, execution in HTML, basic concepts like variables and data types, control structures, functions, objects, arrays, DOM manipulation, asynchronous JavaScript, and error handling. It provides examples and explanations for each topic, making it a useful reference for developers. Key features include inline, internal, and external JavaScript execution methods, as well as modern ES6 syntax and practices.

Uploaded by

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

Java Script

The document is a comprehensive JavaScript cheat sheet covering its structure, execution in HTML, basic concepts like variables and data types, control structures, functions, objects, arrays, DOM manipulation, asynchronous JavaScript, and error handling. It provides examples and explanations for each topic, making it a useful reference for developers. Key features include inline, internal, and external JavaScript execution methods, as well as modern ES6 syntax and practices.

Uploaded by

Reymond Dalupang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

JavaScript Cheat Sheet

JavaScript Structure and Running with HTML

1. Structure of JavaScript

JavaScript follows a structured approach with:

 Declarations (variables, functions, objects, etc.)

 Statements (loops, conditions, operations, etc.)

 Functions (modular reusable code blocks)

 Events (handling user interactions)

 Asynchronous operations (fetching data, timeouts, etc.)

2. Running JavaScript in HTML

To run JavaScript, you can:

Inline JavaScript (inside HTML elements)

<button onclick="alert('Hello!')">Click Me</button>

Internal JavaScript (inside <script> tag)

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script>
function greet() {
alert("Hello, JavaScript!");
}
</script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>

External JavaScript (in separate .js file)

<script src="script.js"></script>

File script.js:

console.log("Hello from JavaScript file!");


Basics

Topic Description Example Explanation


Code

Variables Used to store data values let x = 10; let is used for variables that can be
using var, let, const const y = reassigned. const is used for constants that
20; cannot be reassigned. var is an older way of
var z = 30; declaring variables.

Data Different types: string, let str = str is a string, num is a number, and bool is a
Types number, boolean, object, "Hello"; boolean.
etc. let num =
25;
let bool =
true;

Operators Arithmetic (+, -, *, /), `)


assignment (=, +=),
comparison (==, ===),
logical (&&, `

Control Structures

Topic Description Example Code Explanation

Conditionals Used for let x = 15; This checks if x is greater than 10.
(if-else) decision-making if (x > 10) { If true, it prints "Big"; otherwise,
console.log("Big"); it prints "Small".
} else {
console.log("Small");
}

Switch Case Alternative to let day = 3; The switch statement is an


multiple if switch(day) { alternative to using multiple if-
statements case 1: else checks. It checks the value of
console.log("Monday"); day and prints the corresponding
break; day.
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default: console.log("Other");
}

For Loop Executes a block for (let i = 0; i < 5; i++) { The for loop runs 5 times,
of code a set console.log(i); printing the values of i from 0 to
number of times } 4.

While Loop Runs as long as a let i = 0; The while loop runs as long as i is
condition is true while (i < 5) { less than 5, incrementing i with
console.log(i); each iteration.
i++;
}

Do-While Runs at least let i = 0; The do-while loop guarantees


Loop once before do { that the code will run at least
checking console.log(i); once, then checks if the condition
condition i++; is met before continuing.
} while (i < 5);

Functions & Objects

Topic Description Example Code Explanation

Functions Blocks of function greet(name) { Functions like greet allow you to


reusable code return "Hello, " + name; reuse code. Here, it takes a name
} and returns a greeting.
console.log(greet("John"));

ES6 Arrow Concise const add = (a, b) => a + b; Arrow functions provide a more
Functions function syntax console.log(add(2, 3)); compact syntax for writing
functions.

Objects Collection of let person = { Objects hold key-value pairs. The


key-value pairs name: "John", greet method is a function inside
age: 30, the person object.
greet() { return "Hello, " +
this.name; }
};
console.log(person.greet());

Object Functions let car = { Object methods are functions that


Methods inside objects brand: "Toyota", are associated with an object. Here,
drive() { the drive method prints "Vroom".
console.log("Vroom");
}
};
car.drive();
Arrays & Methods

Topic Description Example Code Explanation

Arrays Collection of let arr = [1, 2, 3]; Arrays hold multiple elements. The
elements arr.push(4); push method adds an item to the
console.log(arr); end of the array.

Array Functions like let doubled = arr.map(num The map method creates a new array
Methods map, filter, reduce => num * 2); by applying a function to each
console.log(doubled); element of the array.

DOM Manipulation & Events

Topic Description Example Code Explanation

DOM Changing document.getElementById("demo").innerText This changes the


Manipulation HTML = "Hello!"; text inside an
elements HTML element
dynamically with the ID demo
to "Hello!".

Events Handling user let button = This adds an event


interactions document.getElementById("myButton"); listener to the
like clicks button.addEventListener("click", () => button, which
alert("Clicked!")); triggers an alert
when clicked.

Asynchronous JavaScript

Topic Description Example Code Explanation

JSON JavaScript let obj = JSON.parse('{"name":"John"}'); JSON.parse()


Object console.log(obj.name); converts a
Notation for JSON string
data into a
exchange JavaScript
object.

Promises Handle fetch('https://jsonplaceholder.typicode.com/posts') The fetch()


asynchronous .then(response => response.json()) function
operations .then(data => console.log(data)); returns a
promise. You
can use .then()
to handle the
result of the
asynchronous
operation.

Async/Await Alternative to async function fetchData() { async/await


promises, let res = await provides a
makes async fetch('https://jsonplaceholder.typicode.com/posts'); cleaner way to
code readable let data = await res.json(); write
console.log(data); asynchronous
} code. The
fetchData(); await keyword
waits for the
promise to
resolve before
moving on.

Storage, Modules & Error Handling

Topic Description Example Code Explanation

Local Store data in the localStorage.setItem("user", localStorage allows you to


Storage browser "John"); store data in the browser. You
let user = can retrieve it with getItem.
localStorage.getItem("user");
console.log(user);

Modules Importing/exporting // module.js Modules allow you to break


(ES6) code between files export function greet() { return up code into reusable
"Hello"; } components. You can
// main.js import/export functions
import { greet } from between files.
'./module.js';
console.log(greet());

Error Catch and handle try { try-catch is used to handle


Handling errors let x = y; errors. The catch block
} catch (err) { handles any errors that occur
console.log("Error:", err); in the try block.
}

You might also like