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

Javascript

The document provides an overview of JavaScript concepts including variable declaration, arrays, functions, and DOM manipulation. It explains how to use methods like .push(), .pop(), and .unshift() for array manipulation, as well as how to change HTML content and styles using JavaScript. Additionally, it covers regular expressions for string manipulation and event handling with addEventListener.

Uploaded by

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

Javascript

The document provides an overview of JavaScript concepts including variable declaration, arrays, functions, and DOM manipulation. It explains how to use methods like .push(), .pop(), and .unshift() for array manipulation, as well as how to change HTML content and styles using JavaScript. Additionally, it covers regular expressions for string manipulation and event handling with addEventListener.

Uploaded by

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

JAVASCRIPT

Declaring a variable means giving it a name. In JavaScript, this is often done with the
let keyword. For example, here is how you would declare a hello variable:
let hello;

Printing

let character = 'Hello';


[Link](character)

Camel case means that the first word in the name is entirely lowercase, but the
following words are all title-cased. Here are some examples of camel case:

let secondCharacter;
--------------------------------------------------------------------------------------------
let profession;
profession="teacher";
let age;
[Link](profession);
[Link](age);

// console output
teacher
undefined

---------------------------------------------------------------------------------------------
An array is a non-primitive data type that can hold a series of values. Non-primitive
data types differ from primitive data types in that they can hold more complex data.
Primitive data types like strings and numbers can only hold one value at a time.

let array = [];


let array = ["first", "second"];
array[0]

let array = [1, 2, 3];


array[1] = 25;
[Link](array); // prints [1, 25, 3]

[Link] returns the number of elements in the array.


-------------------------------------------------------------------------------------------------------

let cities= [ "London", "New York", "Mumbai" ];


[Link](cities);
cities[[Link] - 1 ]="Mexico City";
[Link](cities);

// console output
[ 'London', 'New York', 'Mumbai' ]
[ 'London', 'New York', 'Mexico City' ]

let rows = ["Naomi", "Quincy", "CamperChan"];


[Link]("freeCodeCamp")
[Link](rows);

// console output
[ 'Naomi', 'Quincy', 'CamperChan', 'freeCodeCamp' ]

let rows = ["Naomi", "Quincy", "CamperChan"];


[Link]("freeCodeCamp");
let popped = [Link]();
[Link](popped);
[Link](rows);

//o/p
freeCodeCamp
[ 'Naomi', 'Quincy', 'CamperChan' ]

let rows = ["Naomi", "Quincy", "CamperChan"];


let pushed = [Link]("freeCodeCamp");
[Link](pushed);
[Link](rows);
let popped = [Link]();
[Link](popped);
[Link]();
[Link](rows);
//output
4 //.push() returns the new length of the array, after adding the value you
give it.
[ 'Naomi', 'Quincy', 'CamperChan', 'freeCodeCamp' ]
freeCodeCamp

[ 'Naomi', 'Quincy', 'CamperChan' ]

-------------------------------------------------------------------------------------------------------

A const variable also cannot be uninitialized. This code would throw an error.

const character = "Hello";

for (iterator; condition; iteration) {


logic;
}

for (let i = 0; i < count; i = i + 1) {


[Link](i)
}
-------------------------------------------------------------------------------------------------------
const character = "#";
const count = 8;
const rows = [];

for (let i = 0; i < count; i = i + 1) {


[Link](i);
}

let result = ""

for (const row of rows) {


result = result + row;
}
[Link](result);

// console output
01234567

--------------------------------------------------------------------------------------------------
lineOne = lineOne + "\n" + lineTwo;
const character = "#";
const count = 8;
const rows = [];

for (let i = 0; i < count; i = i + 1) {


[Link]([Link](i));
}

let result = ""

for (const row of rows) {


result = result + row + "\n";
}

[Link](result);

//
#
##
###
####
#####
######
#######

-------------------------------------------------------------------------------------------------------

function name(parameter) {
}

function addTwoNumbers(num1, num2) {


return num1 + num2;
}

const sum = addTwoNumbers(5, 10);


[Link](sum)

//15

strict equality operator.


done === count
The .unshift() method of an array allows you to add a value to the beginning of
the array, unlike .push() which adds the value at the end of the array.
.unshift() returns the new length of the array it was called on.

const numbers = [1, 2, 3];


const unshifted = [Link](5)
[Link](unshifted)
[Link](numbers);

// console output
4
[ 5, 1, 2, 3 ]

the first element of the array, unlike .pop() which


removes the last element. Here is an example of
the .shift() method:

const numbers = [1, 2, 3];

const shifted = [Link]();


[Link](shifted);

const unshifted = [Link](5);


[Link](unshifted);
[Link](numbers);

// console output
1
3
[ 5, 2, 3 ]

----------------------------

const character = "!";


const count = 10;
const rows = [];
let inverted = false;

function padRow(rowNumber, rowCount) {


return " ".repeat(rowCount - rowNumber) + [Link](2 *
rowNumber - 1) + " ".repeat(rowCount - rowNumber);
}
for (let i = 1; i <= count; i++) {
if (inverted) {
[Link](padRow(i, count));
} else {
[Link](padRow(i, count));
}
}

let result = ""

for (const row of rows) {


result = result + row + "\n";
}

[Link](result);

// console output
!
!!!
!!!!!
!!!!!!!
!!!!!!!!!
!!!!!!!!!!!
!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!

JavaScript interacts with the HTML using the Document


Object Model, or DOM. The DOM is a tree of objects that
represents the HTML. You can access the HTML using the
document object, which represents your entire HTML
document.
One method for finding specific elements in your HTML is using the querySelector()
method. The querySelector() method takes a CSS selector as an argument and returns the
first element that matches that selector. For example, to find the <h1> element in your HTML, you
would write:

let button1 = [Link]('#button1')


button1 represents your first button element. These
elements have a special property called onclick, which
you can use to determine what happens when someone clicks
that button.

The innerText property controls the text that appears in


an HTML element. For example:
<p id="info">Demo content</p>

const info = [Link]("#info");


[Link] = "Hello World";

The example above would change the text of the p element from Demo content to
Hello World.

[Link] = goStore;
[Link] = goCave;
[Link] = fightDragon;

function goStore() {
[Link] = "Buy 10 health (10 gold)";
[Link] = "Buy weapon (30 gold)";
[Link] ="Go to town square";
}
You need to wrap the text Store in double quotes. Because
your string is already wrapped in double quotes, you'll
need to escape the quotes around Store. You can escape
them with a backslash \.
[Link] = "You are in the town square. You see a sign that
says \"Store\".";

You are in the town square. You see a sign that says
"Store".

Objects are non primitive data types that store key-value


pairs. Non primitive data types are mutable data types
that are not undefined, null, boolean, number, string, or
symbol. Mutable means that the data can be changed after
it is created.

const cat = {
name :"Whiskers"
}
[Link](cat)
//o/p

{ name: 'Whiskers' }
const cat = {
name: "Whiskers",
"Number of legs": 4,
}
[Link]([Link])
[Link](cat["Number of legs"]);

o/p

Whiskers
4

The style property is used to access the inline style of


an element and the display property is used to set the
visibility of an element.
Here is an example of how to update the display for a paragraph element:

const paragraph = [Link]('p');


[Link] = 'block';
[Link]='block';

In getMonsterAttackValue, change return hit to a


ternary operator that returns hit if hit is
greater than 0, or returns 0 if it is not.

return hit > 0 ? hit: 0;

Update the console statement to print a whole


number between 0 and 9.

[Link]([Link]([Link] * [Link]()))
o/p

1
CHANGE BG COLOR

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>Build a random background color changer</title>
<link rel="stylesheet" href="./[Link]" />
</head>
<body>
<h1>Random Background Color changer</h1>

<main>
<section class="bg-information-container">
<p>Hex Code: <span id="bg-hex-code">#110815</span></p>
</section>

<button class="btn" id="btn">Change Background Color</button>


</main>
<script src="./[Link]"></script>
</body>
</html>

const darkColorsArr = [
"#2C3E50",
"#34495E",
"#2C2C2C",
"#616A6B",
"#4A235A",
"#2F4F4F",
"#0E4B5A",
"#36454F",
"#2C3E50",
"#800020",
];

function getRandomIndex() {
const randomIndex = [Link]([Link] *
[Link]());
return randomIndex;
}

const body = [Link]("body");


const bgHexCodeSpanElement = [Link]("#bg-hex-
code");

function changeBackgroundColor() {
const color = darkColorsArr[getRandomIndex()];

[Link] = color;
[Link] = color;
}
const btn = [Link]("#btn");

[Link] = changeBackgroundColor;
To match specific characters in a string, you can
use Regular Expressions or "regex" for short.
Regex in JavaScript is indicated by a pattern wrapped in forward slashes.
The following example will match the string literal "hello":

const regex = /hello/;

The current pattern will match the exact text


"hello", which is not the desired behavior.
Instead, you want to search for +, -, or spaces.
Replace the pattern in your regex variable with \
+- to match plus and minus characters.
const regex = /\+-/;

In regex, shorthand character classes allow you to


match specific characters without having to write
those characters in your pattern. Shorthand
character classes are preceded with a backslash
(\). The character class \s will match any
whitespace character. Add this to your regex
pattern.
const regex = /\+-\s/;

To tell the pattern to match each of these


characters individually, you need to turn them
into a character class. This is done by wrapping
the characters you want to match in brackets. For
example, this pattern will match the characters h,
e, l, or o:
const regex = /[helo]/;
Turn your +-\s pattern into a character class. Note that you no longer need to escape
the + character, because you are using a character class.
const regex = /[+-\s]/;

JavaScript provides a .replace() method that enables you


to replace characters in a string with another string.
This method accepts two arguments. The first argument is
the character sequence to be replaced, which can be
either a string or a regex pattern. The second argument
is the string that replaces the matched sequence.
Since strings are immutable, the replace method returns a new string with the
replaced characters.
In this example, the replace method is used to replace all instances of the
letter l with the number 1 in the string hello.
"hello".replace(/l/g, "1");

function cleanInputString(str) {
[Link]("original string: ", str);
const regex = /[+-\s]/g;
return [Link](regex, '');
}

[Link](cleanInputString("+-99"));

output
original string: +-99
99
function addEntry() {
const targetId = '#' + [Link];
const targetInputContainer = [Link](`$
{targetId} .input-container`);

function addEntry() {
const targetInputContainer = [Link](`#$
{[Link]} .input-container`);
}

To get all of the number inputs, you can use the querySelectorAll()
method.
The querySelectorAll() method returns a NodeList of all the
elements that match the selector. A NodeList is an array-like object, so you
can access the elements using bracket notation.
Declare an entryNumber variable and give it the value of
[Link](). You do not need to
pass an argument to the query selector yet.

function addEntry() {
const targetInputContainer = [Link](`#$
{[Link]} .input-container`);
const entryNumber = [Link]();
}

const entryNumber =
[Link]('input[type="text"]').length;
o see your new HTML content for the
targetInputContainer, you will need to use the
innerHTML property.
The innerHTML property sets or returns the HTML content inside an element.

Here is a form element with a label and input element nested inside.

<form id="form">
<label for="first-name">First name</label>
<input id="first-name" type="text">
</form>

If you want to add another label and input element inside the form, then
you can use the innerHTML property as shown below:

const formElement = [Link]("form");


const formContent = `
<label for="last-name">Last name</label>
<input id="last-name" type="text">
`;
[Link] += formContent;
Use the addition assignment operator += to append your HTMLString variable to
[Link].

function addEntry() {
const targetInputContainer = [Link](`#$
{[Link]} .input-container`);
const entryNumber =
[Link]('input[type="text"]').length;
const HTMLString = `
<label for="${[Link]}-${entryNumber}-name">Entry
${entryNumber} Name</label>
<input type="text" id="${[Link]}-${entryNumber}-
name" placeholder="Name" />
<label for="${[Link]}-${entryNumber}-
calories">Entry ${entryNumber} Calories</label>
<input
type="number"
min="0"
id="${[Link]}-${entryNumber}-calories"
placeholder="Calories"
/>`;
[Link] += HTMLString;
}

Button click

The following example uses the addEventListener


method to add a click event to a button. When the
button is clicked, the printName function is called.
<button class="btn">Print name</button>

const button = [Link]('.btn');


function printName() {
[Link]("Jessica");
}
[Link]('click', printName);

The addEventListener method takes two arguments. The first is the


event to listen to. (Ex. 'click') The second is the callback function, or
the function that runs when the event is triggered.
Call the .addEventListener() method on the addEntryButton.
Pass in the string "click" for the first argument and the addEntry
function for the second argument.
[Link]('click',addEntry);

Your other bug occurs if you add a Breakfast entry,


fill it in, then add a second Breakfast entry. You'll
see that the values you added disappeared.
This is because you are updating innerHTML directly, which does not
preserve your input content. Change your innerHTML assignment to use the
insertAdjacentHTML() method of targetInputContainer instead.
function addEntry() {
const targetInputContainer = [Link](`#$
{[Link]} .input-container`);
const entryNumber =
[Link]('input[type="text"]').length + 1;
const HTMLString = `
<label for="${[Link]}-${entryNumber}-name">Entry
${entryNumber} Name</label>
<input type="text" id="${[Link]}-${entryNumber}-
name" placeholder="Name" />
<label for="${[Link]}-${entryNumber}-
calories">Entry ${entryNumber} Calories</label>
<input
type="number"
min="0"
id="${[Link]}-${entryNumber}-calories"
placeholder="Calories"
/>`;
[Link]();
}

[Link]("beforeend" ,HTMLString);

for loop

The list parameter is going to be the result of a


query selector, which will return a NodeList. A
NodeList is a list of elements like an array. It
contains the elements that match the query selector.
You will need to loop through these elements in the
list.
Inprevious steps, you learned how to loop through an array using a for loop.
You can also use a for...of loop to loop through an array and a NodeList.
A for...of loop is used to iterate over elements in an iterable object like an
array. The variable declared in the loop represents the current element being
iterated over.
for (const element of elementArray) {
[Link](element);
}

Rock Paper Scissors

function getRandomComputerResult() {
const options = ["Rock", "Paper", "Scissors"];
const randomIndex = [Link]([Link]() * [Link]);
return options[randomIndex];
}

function hasPlayerWonTheRound(player, computer) {


return (
(player === "Rock" && computer === "Scissors") ||
(player === "Scissors" && computer === "Paper") ||
(player === "Paper" && computer === "Rock")
);
}

let playerScore = 0;
let computerScore = 0;

function getRoundResults(userOption) {
const computerResult = getRandomComputerResult();

if (hasPlayerWonTheRound(userOption, computerResult)) {
playerScore++;
return `Player wins! ${userOption} beats ${computerResult}`;
} else if (computerResult === userOption) {
return `It's a tie! Both chose ${userOption}`;
} else {
computerScore++;
return `Computer wins! ${computerResult} beats ${userOption}`;
}
}

const playerScoreSpanElement = [Link]("player-


score");
const computerScoreSpanElement =
[Link]("computer-score");
const roundResultsMsg = [Link]("results-msg");
const winnerMsgElement = [Link]("winner-msg");
const optionsContainer = [Link](".options-
container");
const resetGameBtn = [Link]("reset-game-btn");

function showResults(userOption) {
[Link] = getRoundResults(userOption);
[Link] = computerScore;
[Link] = playerScore;

if (playerScore === 3 || computerScore === 3) {


[Link] = `${
playerScore === 3 ? "Player" : "Computer"
} has won the game!`;

[Link] = "block";
[Link] = "none";
}

};
function resetGame() {
playerScore =0 ;
computerScore = 0;
[Link] = playerScore;
[Link]= computerScore;
[Link]='none';
[Link] ='block';
[Link] ='';
[Link]='';
};

[Link]("click", resetGame);
const rockBtn = [Link]("rock-btn");
const paperBtn = [Link]("paper-btn");
const scissorsBtn = [Link]("scissors-btn");

[Link]("click", function () {
showResults("Rock");
});

[Link]("click", function () {
showResults("Paper");
});

[Link]("click", function () {
showResults("Scissors");
});

Web Audio API and how to use it to play songs. All


modern browsers support the Web Audio API, which lets
you generate and process audio in web applications.

const audio = new Audio();

Since users will be able to shuffle and delete songs


from the playlist, you will need to create a copy of
the allSongs array without mutating the original.
This is where the spread operator comes in handy.
The spread operator (...) allows you to copy all elements from one array into
another. It can also be used to concatenate multiple arrays into one. In the
example below, both arr1 and arr2 have been spread into combinedArr:

const arr1 = [1, 2, 3];


const arr2 = [4, 5, 6];

const combinedArr = [...arr1, ...arr2];


[Link](combinedArr); // Output: [1, 2, 3, 4, 5,
6]
you will be working with arrow functions. The next
few steps will focus on teaching you the basics of
arrow functions.

An arrow function is an anonymous function expression and a


shorter way to write functions. Anonymous means that the
function does not have a name. Arrow functions are always
anonymous.
Here is the basic syntax:
() => {}

By assigning the arrow function definition to a variable, you bind


it to an identifier.
const exampleFunction = () => {
// code goes here
}

const printGreeting=()=>{
[Link]("Hello there!")
}

Just like regular functions, arrow functions can


accept multiple parameters.
Here is an example of a named arrow function with one parameter:
const greet = (name) => {
[Link](`Hello, ${name}!`);
};

If the function only has one parameter, you can omit the parentheses
around the parameter list like this:
const greet = name => {
[Link](`Hello, ${name}!`);
};

Create a new named arrow function called printMessage that has one
parameter called org. Inside the body of that function, add a console
statement. Inside that console statement, add the template literal ${org}
is awesome!.
const printMessage = org =>{
[Link](`${org} is awesome!`);
}
printMessage("freeCodeCamp")

If the arrow function is returning a simple


expression, you can omit the return keyword and
the curly braces {}. This is called an implicit
return.
const multiplyTwoNumbers = (num1, num2) => num1 *
num2;

If your arrow function has multiple lines of code


in the function body, then you need to use the
return keyword and the curly braces {}.
const getTax = (price) => {
const taxRate = 0.08;
const tax = price * taxRate;
return tax;
};

const printGreeting = () => {


[Link]('Hello there!');
}
printGreeting();

const printMessage = org => {


[Link](`${org} is awesome!`);
}
printMessage('freeCodeCamp');
const addTwoNumbers = (num1, num2) => num1 + num2
[Link](addTwoNumbers(3,4));

The map() method is used to iterate through an


array and return a new array. It's helpful when
you want to create a new array based on the values
of an existing array. For example:

const numbers = [1, 2, 3];


const doubledNumbers = [Link]((number) =>
number * 2); // doubledNumbers will be [2, 4, 6]

Notice that the map() method takes a function as


an argument. This is called a callback function,
which is a function that is passed to another
function as an argument. In the example above, the
callback function is (number) => number * 2, and
it's run on each element in the numbers array. The
map() method then returns a new array with the
results.
Pass in a callback function to the map() method.
The callback function should take song as a
parameter, use the arrow function syntax, and have
an empty body.

const songsHTML = [Link](song=> {});


The join() method is used to concatenate all the
elements of an array into a single string. It
takes an optional parameter called a separator
which is used to separate each element of the
array. For example:

const exampleArr = ["This", "is", "a",


"sentence"];
const sentence = [Link](" "); //
Separator takes a space character
[Link](sentence); // Output: "This is a
sentence"

Chain the join() method to your map() method and pass in an empty
string for the separator.
Optional chaining (?.) helps prevent errors when
accessing nested properties that might be null or
undefined. For example:
const user = {
name: "Quincy",
address: {
city: "San Francisco",
state: "CA",
country: "USA",
},
};

// Accessing nested properties without optional


chaining
const state = [Link]; // CA

// Accessing a non-existent nested property with


optional chaining
const zipCode = [Link]?.zipCode; // Returns
undefined instead of throwing an error
The find() method retrieves the first element
within an array that fulfills the conditions
specified in the provided callback function. If no
element satisfies the condition, the method
returns undefined.

In the example below, the find() method is used to find the first number
greater than 25:
const numbers = [10, 20, 30, 40, 50];

// Find the first number greater than 25


const foundNumber = [Link]((number) =>
number > 25);
[Link](foundNumber); // Output: 30

const playSong = (id) => {


const song= userData?.[Link]((song)=> [Link] === id);
};

To get the index for the current song, you can use
the indexOf() method. The indexOf() array method
returns the first index at which a given element
can be found in the array, or -1 if the element is
not present.

const animals = ["dog", "cat", "horse"];

[Link]("cat") // 1

const getCurrentSongIndex = () => {


return userData?.[Link](userData?.currentSong)
}
Loop through the playlistSongElements with a forEach
method.
The forEach method is used to loop through an array and perform a function
on each element of the array. For example, suppose you have an array of
numbers and you want to log each number to the console.

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

// Using forEach to iterate through the array


[Link]((number) => {
[Link](number); // 1, 2, 3, 4, 5
});

If the playlist is empty, you need to create a


resetButton element and a text for it. This button
will only show up if the playlist is empty.
createElement() is a DOM method you can use to dynamically
create an element using JavaScript. To use createElement(), you call
it, then pass in the tag name as a string:

// syntax
[Link](tagName)

// example
[Link]('div')

You can also assign it to a variable:


const divElement = [Link]('div')
if (userData?.[Link] === 0) {
const resetButton = [Link]("button")
}
Now that you've created the button, you need to
assign it a text. To do this, you need to use the
createTextNode() method of DOM.
The createTextNode() method is used to create a text node. To use it,
you call it and pass in the text as a string:
[Link]("your text")

You can also assign it to a variable:


const myText = [Link]("your
text")
const resetText = [Link]("Reset Playlist")

The Date object has a number of methods that allow


you to get the date and time in different formats.
One of those is the .getDate() method, which returns a number
between 1 and 31 that represents the day of the month for that date. For
example:
const date = new Date();
const dayOfTheMonth = [Link]();
[Link](dayOfTheMonth); // 20
const day = [Link]();

In JavaScript, the change event is used to detect


when the value of an HTML element has changed:
[Link]("change", () => {

});

[Link]("change", () => {
});
When a user makes a selection from the dropdown
menu, the function should get the user's value and
display the date in their chosen date format. To
do this, you can use the switch statement.
A switch statement is used to compare an expression against multiple
possible values and execute different code blocks based on the match. It's
commonly used for branching logic.
For example, here's how to compare the expression dayOfWeek against
possible values:
switch (dayOfWeek) {
case 1:
[Link]("It's Monday!");
break;
case 2:
[Link]("It's Tuesday!");
break;
// ...cases for other workdays
default:
[Link]("It's the weekend!");
}

The split method takes in a parameter known as a


separator. The separator is used to tell the
computer where each split should occur.
Here is an example of using an empty string as a separator:
// returns ["h", "e", "l", "l", "o"]
"hello".split("");

Other examples of separators can include a space " ", or a hyphen "-".
If you don't provide a separator, the method will return an array with the
original string as the only element.
To reverse an array of elements, you can use the
reverse method. This method reverses the order of
the elements in the array in place. The first
element becomes the last, and the last element
becomes the first.
Here is an example of using the reverse method:
// returns [5, 4, 3, 2, 1]
[1, 2, 3, 4, 5].reverse();

Chain the reverse method to your split method. Open up the console
again to see the result.
Remember that you learned how to chain methods in the previous project like
this:
method1().method2().method3();

const exampleSentence = "selur pmaCedoCeerf".split("").reverse();


[Link](exampleSentence);

// returns "1-2-3-4-5"
[1, 2, 3, 4, 5].join("-");
DATE-MONTH-YEAR-HOUR-MIN
const currentDateParagraph = [Link]("current-
date");
const dateOptionsSelectElement = [Link]("date-
options");

const date = new Date();


const day = [Link]();
const month = [Link]() + 1;
const year = [Link]();
const hours = [Link]();
const minutes = [Link]();

const formattedDate = `${day}-${month}-${year}`;


[Link] = formattedDate;

[Link]("change", () => {

switch ([Link]) {
case "yyyy-mm-dd":
[Link] = formattedDate
.split("-")
.reverse()
.join("-");
break;
case "mm-dd-yyyy-h-mm":
[Link] = `${month}-${day}-${year} $
{hours} Hours ${minutes} Minutes`;
break;
default:
[Link] = formattedDate;
}
});

The object destructuring syntax allows you to


unpack values from arrays and objects:
const developerObj = {
name: "Jessica Wilkins",
isDeveloper: true
};

// Object destructuring
const { name, isDeveloper } = developerObj;

const{sport,team} = myFavoriteFootballTeam;

Function parameters can be initialized with default


values. If a function is called without an argument,
then the default value will be used:

const greeting = (name = "Anonymous") => {

return "Hello " + name;


}

[Link](greeting("John")); // Hello John


[Link](greeting()); // Hello Anonymous

The toggle method will add the class if it is not


present on the element, and remove the class if it is
present on the element.

[Link]("click",()=>{
[Link]("hidden");
})

A modal is an element that prevents all interaction


with elements outside it until the modal has been
dismissed.
The HTML dialog element has a showModal() method that can be used to
display a modal dialog box on a web page.
[Link]();
If the user clicks the Cancel button, you
want to cancel the process and close the
modal so the user can continue editing. The
HTML dialog element has a close() method
that can be used to close a modal dialog box
on a web page.
[Link]();

unshift() is an array method that is used to add one


or more elements to the beginning of an array.
const arr = [1, 2, 3];
[Link](0);

[Link](taskObj)

For each

[Link](({id, title, date, description})=>{}

)
splice() is an array method that modifies arrays by removing,
replacing, or adding elements at a specified index, while also returning
the removed elements. It can take up to three arguments: the first one
is the mandatory index at which to start, the second is the number of
items to remove, and the third is an optional replacement element.

const fruits = ["mango", "date", "cherry", "banana",


"apple"];
// Remove date and cherry from the array starting at
index 1
const removedFruits = [Link](1, 2);

[Link](fruits); // [ 'mango', 'banana',


'apple' ]
[Link](removedFruits); // [ 'date', 'cherry' ]

[Link]();
[Link](dataArrIndex,1);

------------------------------------------------------------------------------------------------

const myTaskArr = [
{ task: "Walk the Dog", date: "22-04-2022" },
{ task: "Read some books", date: "02-11-2023" },
{ task: "Watch football", date: "10-08-2021" },
];

[Link]("data", [Link](myTaskArr));

[Link]();

const getTaskArr = [Link]("data")


[Link](getTaskArr)

const getTaskArrObj = [Link]([Link]("data"));


[Link](getTaskArrObj);

const removeSpecialChars = (val) => {


return [Link]().replace(/[^A-Za-z0-9\-\s]/g, '')
}
DECIMAL TO BINARY CONVERTER

const numberInput = [Link]("number-input");


const convertBtn = [Link]("convert-btn");
const result = [Link]("result");

const decimalToBinary = (input) => {


const inputs = [];
const quotients = [];
const remainders = [];

if (input === 0) {
[Link] = "0";
return;
}

while (input > 0) {


const quotient = [Link](input / 2);
const remainder = input % 2;

[Link](input);
[Link](quotient);
[Link](remainder);
input = quotient;
}

[Link]("Inputs: ", inputs);


[Link]("Quotients: ", quotients);
[Link]("Remainders: ", remainders);

[Link] = [Link]().join("");
};

const checkUserInput = () => {


if (
![Link] ||
isNaN(parseInt([Link])) ||
parseInt([Link]) < 0
){
alert("Please provide a decimal number greater than or equal to 0");
return;
}

decimalToBinary(parseInt([Link]));
[Link] = "";
};

[Link]("click", checkUserInput);

[Link]("keydown", (e) => {


if ([Link] === "Enter") {
checkUserInput();
}
});

count up and down of a no

const countDownAndUp = (number) => {


[Link](number);

if (number === 0) {
[Link]("Reached base case");
return;
} else {
countDownAndUp(number - 1);
[Link](number);
}
};

countDownAndUp(3);

Animation
Use the setTimeout function to add a one second delay before the text
"Code" is logged to the console.
setTimeout(() => {
[Link]("Code");

}, 1000);

Instead of using the .match() method, you can use the


.test() method of a regular expression to test if a string
matches the pattern. Unlike .match(), .test() returns
a boolean value indicating whether or not the string
matches the pattern.

The next regular expression you will work on is one that matches mentions of
dollar amounts.
Start by declaring a dollarRegex variable, and assign it a case-insensitive regular expression
that matches the text dollars.

const dollarRegex=/dollars/i

spam or not spam


const messageInput = [Link]("message-
input");
const result = [Link]("result");
const checkMessageButton = [Link]("check-
message-btn");

const helpRegex = /please help|assist me/i;


const dollarRegex = /[0-9]+\s*(?:hundred|thousand|million|billion)?\
s+dollars/i;
const freeRegex = /(?:^|\s)fr[e3][e3] m[o0]n[e3]y(?:$|\s)/i;
const stockRegex = /(?:^|\s)[s5][t7][o0][c{[(]k [a@4]l[e3]r[t7](?:$|\s)/i;
const dearRegex = /dear friend/i;

const denyList = [helpRegex, dollarRegex, freeRegex, stockRegex,


dearRegex];

const isSpam = (msg) => [Link]((regex) => [Link](msg));

[Link]("click", () => {
if ([Link] === "") {
alert("Please enter a message.");
return;
}

[Link] = isSpam([Link])
? "Oh no! This looks like a spam message."
: "This message does not seem to contain any spam.";
[Link] = "";
});

Create a numbers variable and assign it the value of


[Link](). Remember that .map() creates a new array,
instead of mutating the original array.

const numbers = [Link]()

Mode calculation
const numbersArr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1,
2, 3, 4];
const counts = {};
[Link]((el) => {
if (counts[el]) {
counts[el] += 1;
} else {
counts[el] = 1;
}
});
SPREAD SHEET

the document object has a .createElement() method which allows you


to dynamically create new HTML elements.
const label =[Link]("div")

the className of the label element to "label", and set the


textContent to the name parameter.
const label = [Link]("div");
[Link]="label";
[Link]=name;

.appendChild() method to add your label element to the container


element.
[Link] = () => {
const container = [Link]("container");
const createLabel = (name) => {
const label = [Link]("div");
[Link] = "label";
[Link] = name;
[Link](label) ;
}
}
Declare an empty range function which takes a start and end parameter.
Use the Array() constructor and implicitly return an empty array.
const range = (start,end) =>Array()
const range = (start, end) => Array(end-start+1);

charCodeAt() :
const charRange = (start, end) => range([Link](0),
[Link](0));
const userId = 1;
const firstName = "John";
const loggedIn = true;

const user = {
userId,
firstName,
loggedIn,
};

[Link](user);

const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi;

g- global
i -case insensitive
([A-J]) - alphbet A – J

([1-9][0-9]?) 1st digit 1-9 2nd digit 0-9

Destruction

Array Destructuring
Array destructuring allows extracting values based on their position in the array.
JavaScript

const numbers = [1, 2, 3];


const [first, second, third] = numbers;
[Link](first); // Output: 1
[Link](second); // Output: 2
[Link](third); // Output: 3
Object Destructuring
Object destructuring extracts values based on the property names.
JavaScript

const person = { name: "John", age: 30, city: "New York"


};
const { name, age, city } = person;
[Link](name); // Output: John
[Link](age); // Output: 30
[Link](city); // Output: New York

Destructuring with Default Values


Default values can be assigned in case the property or array element does not exist.
JavaScript

const person = { name: "John" };


const { name, age = 30 } = person;
[Link](name); // Output: John
[Link](age); // Output: 30

Destructuring with Renaming


Properties can be extracted and assigned to variables with different names.
JavaScript

const person = { name: "John" };


const { name: userName } = person;
[Link](userName); // Output: John
Nested Destructuring
Destructuring can be applied to nested objects and arrays.
JavaScript

const company = {
name: "Tech Inc",
employees: [{ name: "John", age: 30 }, { name: "Jane",
age: 25 }]
};
const { name: companyName, employees: [, { name:
employee2Name }] } = company;
[Link](companyName); // Output: Tech Inc
[Link](employee2Name); // Output: Jane

Destructuring Function Parameters


Destructuring can be used directly in function parameters.
JavaScript

function printPersonInfo({ name, age }) {


[Link](`Name: ${name}, Age: ${age}`);
}
const person = { name: "John", age: 30 };
printPersonInfo(person); // Output: Name: John, Age: 30

NEW KEYWORD

instantiate a new ShoppingCart object and assign it to a


variable

const cart = new ShoppingCart()

Spread operator
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray]; // [1, 2, 3]

inverting the value of isCartShowing.

isCartShowing = ![Link]

CLEARING A CHART CHECKING WHEATHER ARRAY IS EMPTY

clearCart() {
if (![Link]) {
alert("Your shopping cart is already empty");
return;
}

const isCartCleared = confirm(


"Are you sure you want to clear all items from your shopping cart?"
);

if (isCartCleared) {
[Link] = [];
[Link] = 0;
[Link] = "";
[Link] = 0;
[Link] = 0;
[Link] = 0;
[Link] = 0;
}
}
GETCONTEXT

The getContext() method in JavaScript is used to obtain the


rendering context of a <canvas> element. This context
provides the tools and methods for drawing graphics,
shapes, text, and images onto the canvas. It takes one
parameter, the context type, which specifies the type of
rendering context to retrieve. Common context types
include "2d" for two-dimensional graphics and "webgl" or
"webgl2" for three-dimensional graphics.

The Canvas API can be used to create graphics in games


using JavaScript and the HTML canvas element.

Canvas

The innerWidth property is a number that represents the


interior width of the browser window.
create the player's shape by calling the fillRect() method
on the ctx object which you instantiated earlier.
fillRect(x, y, width, height)

fetch

There is a method called fetch that allows code to


receive data from an API by sending a GET request.
Here is how you can make a GET request with the fetch() method:
fetch("url-goes-here")

The await keyword waits for a promise to resolve and


returns the result.
const example = async () => {
const data = await
fetch("[Link]
[Link](data);
}
W3 Schools

Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.

An equal sign is used to assign values to variables.


In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
let x;
x = 6;

The general rules for constructing names for


variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter.
• Names can also begin with $ and _ (but we will not use it in this tutorial).
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript Let
The let keyword was introduced in ES6 (2015)

Variables declared with let have Block Scope

Variables declared with let must be Declared before use

Variables declared with let cannot be Redeclared in the same scope

Block Scope
Before ES6 (2015), JavaScript did not have Block Scope.
JavaScript had Global Scope and Function Scope.
ES6 introduced the two new JavaScript keywords: let and const.

These two keywords provided Block Scope in JavaScript:

Example
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here

Global Scope
Variables declared with the var always have Global Scope.

Variables declared with the var keyword can NOT have block scope:

Example
Variables declared with varinside a { } block can be accessed from outside the block:

{
var x = 2;
}
// x CAN be used here
Cannot be Redeclared
Variables defined with let can not be redeclared.

You can not accidentally redeclare a variable declared with let.

With let you can not do this:

let x = "John Doe";

let x = 0;
Variables defined with var can be redeclared.

With var you can do this:

var x = "John Doe";

var x = 0;

Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.

Redeclaring a variable inside a block will also redeclare the variable outside the block:

Example
var x = 10;
// Here x is 10

{
var x = 2;
// Here x is 2
}

// Here x is 2
Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the block:

Example
let x = 10;
// Here x is 10

{
let x = 2;
// Here x is 2
}
// Here x is 10

Difference Between var, let and const


Scope Redeclare Reassign Hoisted Binds this
var No Yes Yes Yes Yes
let Yes No Yes No No
const Yes No No No No

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?


var does not have to be declared.

var is hoisted.

var binds to this.

Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:

Example
var x = 2;
// Now x is 2

var x = 3;
// Now x is 3
With let, redeclaring a variable in the same block is NOT allowed:

Example
var x = 2; // Allowed
let x = 3; // Not allowed

{
let x = 2; // Allowed
let x = 3; // Not allowed
}

{
let x = 2; // Allowed
var x = 3; // Not allowed
}
Redeclaring a variable with let, in another block, IS allowed:

Example
let x = 2; // Allowed

{
let x = 3; // Allowed
}

{
let x = 4; // Allowed
}

Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

Example
This is OK:
carName = "Volvo";
var carName;

Variables defined with let are also hoisted to the top of the block, but not initialized.

Meaning: Using a let variable before it is declared will result in a ReferenceError:

Example
carName = "Saab";
let carName = "Volvo";

JavaScript Const
The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared


Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Must be Assigned
JavaScript const variables must be assigned a value when they are declared:

Correct
const PI = 3.14159265359;

Constant Objects and Arrays


The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.


Because of this you can NOT:
• Reassign a constant value
• Reassign a constant array
• Reassign a constant object
But you CAN:
• Change the elements of constant array
• Change the properties of constant object

Constant Arrays
You can change the elements of a constant array:

Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:


cars[0] = "Toyota";

// You can add an element:


[Link]("Audi");
But you can NOT reassign the array:

Example
const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"]; // ERROR


What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?


var does not have to be declared.

var is hoisted.

var binds to this.

JavaScript has 8 Datatypes


String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object

You might also like