Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 7

do…while Loop

A “do...while” loop works similarly to “for” and “while” loops, but it has a
different syntax.

Here's an example of counting from 1 to 10 using a “do...while” loop:

let i = 1;
do {
console.log(i);
i++;
} while (i <= 10);
In this example:

You initialize the variable "i" to 1 before the loop starts


The “do...while” loop begins by executing the code block, which logs the value of
"i" using “console.log(i)”
After each run of the loop, "i" incrementally increases by 1 using “i++”
The loop continues to run as long as the condition "i <= 10" is true
The output of this code will be the same as in the previous examples:

1
2
3
4
5
6
7
8
9
10
for…in Loop
The “for...in” loop is used to iterate over the properties of an object (a data
structure that holds key-value pairs).

It's particularly handy when you want to go through all the keys or properties of
an object and perform an operation on each of them.

Here's the basic structure of a “for...in” loop:

for (variable in object) {


// Code to be executed for each property
}
And here’s an example of a “for...in” loop in action:

const person = {
name: "Alice",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key, person[key]);
}
In this example:

You have an object named “person” with the properties “name,” “age,” and “city”
The “for...in” loop iterates over the keys (in this case, "name," "age," and
"city") of the “person” object
Inside the loop, it logs both the property name (key) and its corresponding value
in the “person” object
The output of this code will be:

name Alice
age 30
city New York
The “for...in” loop is a powerful tool when you want to perform tasks like data
extraction or manipulation.

Functions
A function is a block of code that performs a particular action in your code. Some
common functions in JavaScript are:

alert() Function
This function displays a message in a pop-up dialog box in the browser. It's often
used for simple notifications, error messages, or getting the user's attention.

Take a look at this sample code:

alert("Hello, world!");
When you call this function, it opens a small pop-up dialog box in the browser with
the message “Hello, world!” And a user can acknowledge this message by clicking an
"OK" button.

prompt() Function
This function displays a dialog box where the user can enter an input. The input is
returned as a string.

Here’s an example:

let name = prompt("Please enter your name: ");


console.log("Hello, " + name + "!");
In this code, the user is asked to enter their name. And the value they provide is
stored in the name variable.

Later, the code uses the name to greet the user by displaying a message, such as
"Hello, [user's name]!"

confirm() Function
This function shows a confirmation dialog box with "OK" and "Cancel" buttons. It
returns “true” if the user clicks "OK" and “false” if they click "Cancel."

Let’s illustrate with some sample code:

const isConfirmed = confirm("Are you sure you want to continue?");


if (isConfirmed) {
console.log("true");
} else {
console.log("false");
}
When this code is executed, the dialog box with the message "Are you sure you want
to continue?" is displayed, and the user is presented with "OK" and "Cancel"
buttons.

The user can click either the "OK" or "Cancel" button to make their choice.

The “confirm()” function then returns a boolean value (“true” or “false”) based on
the user's choice: “true” if they click "OK" and “false” if they click "Cancel."

console.log() Function
This function is used to output messages and data to the browser's console.

Sample code:

console.log("This is the output.");


You probably recognize it from all our code examples from earlier in this post.

parseInt() Function
This function extracts and returns an integer from a string.

Sample code:

const stringNumber = "42";


const integerNumber = parseInt(stringNumber);
In this example, the “parseInt()” function processes the string and extracts the
number 42.

The extracted integer is then stored in the variable “integerNumber.” Which you can
use for various mathematical calculations.

parseFloat() Function
This function extracts and returns a floating-point number (a numeric value with
decimal places).

Sample code:

const stringNumber = "3.14";


const floatNumber = parseFloat(stringNumber);
In the example above, the “parseFloat()” function processes the string and extracts
the floating-point number 3.14.

The extracted floating-point number is then stored in the variable “floatNumber.”

Strings
A string is a data type used to represent text.

It contains a sequence of characters, such as letters, numbers, symbols, and


whitespace. Which are typically enclosed within double quotation marks (" ").

Here are some examples of strings in JavaScript:

const name = "Alice";


const number = "82859888432";
const address = "123 Main St.";
There are a lot of methods you can use to manipulate strings in JS code. These are
most common ones:

toUpperCase() Method
This method converts all characters in a string to uppercase.

Example:

let text = "Hello, World!";


let uppercase = text.toUpperCase();
console.log(uppercase);
In this example, the “toUpperCase()” method processes the text string and converts
all characters to uppercase.

As a result, the entire string becomes uppercase.


The converted string is then stored in the variable uppercase, and the output in
your console is "HELLO, WORLD!"

toLowerCase() Method
This method converts all characters in a string to lowercase

Here’s an example:

let text = "Hello, World!";


let lowercase = text.toLowerCase();
console.log(lowercase);
After this code runs, the “lowercase” variable will contain the value "hello,
world!" Which will then be the output in your console.

concat() Method
The “concat()” method is used to combine two or more strings and create a new
string that contains the merged text.

It does not modify the original strings. Instead, it returns a new string that
results from the combination of the original strings (called the concatenation).

Here's how it works:

const string1 = "Hello, ";


const string2 = "world!";
const concatenatedString = string1.concat(string2);
console.log(concatenatedString);
In this example, we have two strings, “string1” and “string2.” Which we want to
concatenate.

We use the “concat()” method on “string1” and provide “string2” as an argument (an
input value within the parentheses). The method combines the two strings and
creates a new string, stored in the “concatenatedString” variable.

The program then outputs the end result to your console. In this case, that’s
“Hello, world!”

match() Method
The “match()” method is used to search a string for a specified pattern and return
the matches as an array (a data structure that holds a collection of values—like
matched substrings or patterns).

It uses a regular expression for that. (A regular expression is a sequence of


characters that defines a search pattern.)

The “match()” method is extremely useful for tasks like data extraction or pattern
validation.

Here’s a sample code that uses the “match()” method:

const text = "The quick brown fox jumps over the lazy dog";
const regex = /[A-Za-z]+/g;
const matches = text.match(regex);
console.log(matches);
In this example, we have a string named “text.”

Then, we use the “match()” method on the “text” string and provide a regular
expression as an argument.
This regular expression, “/[A-Za-z]+/g,” does two things:

It matches any letter from “A” to “Z,” regardless of whether it's uppercase or
lowercase
It executes a global search (indicated by “g” at the end of the regular
expression). This means the search doesn't stop after the first match is found.
Instead, it continues to search through the entire string and returns all matches.
After that, all the matches are stored in the “matches” variable.

The program then outputs these matches to your console. In this case, it will be an
array of all the words in the sentence "The quick brown fox jumps over the lazy
dog."

charAt() Method
The “charAt()” method is used to retrieve the character at a specified index
(position) within a string.

The first character is considered to be at index 0, the second character is at


index 1, and so on.

Here’s an example:

const text = "Hello, world!";


const character = text.charAt(7);
console.log(character);
In this example, we have the string “text,” and we use the “charAt()” method to
access the character at index 7.

The result is the character "w" because "w" is at position 7 within the string.

replace() Method
The “replace()” method is used to search for a specified substring (a part within a
string) and replace it with another substring.

It specifies both the substring you want to search for and the substring you want
to replace it with.

Here's how it works:

const text = "Hello, world!";


const newtext = text.replace("world", "there");
console.log(newtext);
In this example, we use the “replace()” method to search for the substring "world"
and replace it with "there."

The result is a new string (“newtext”) that contains the replaced text. Meaning the
output is, “Hello, there!”

substr() Method
The “substr()” method is used to extract a portion of a string, starting from a
specified index and extending for a specified number of characters.

It specifies the starting index from which you want to begin extracting characters
and the number of characters to extract.

Here's how it works:

const text = "Hello, world!";


const substring = text.substr(7, 5);
console.log(substring);
In this example, we use the “substr()” method to start extracting characters from
index 7 (which is “w”) and continue for five characters.

The output is the substring "world."

(Note that the first character is always considered to be at index 0. And you start
counting from there on.)

Events
Events are actions that happen in the browser, such as a user clicking a button, a
webpage finishing loading, or an element on the page being hovered over with a
mouse.

Understanding these is essential for creating interactive and dynamic webpages.


Because they allow you to respond to user actions and execute code accordingly.

Here are the most common events supported by JavaScript:

onclick Event
The “onclick” event executes a function or script when an HTML element (such as a
button or a link) is clicked by a user.

Here’s the code implementation for this event:

<button id="myButton" onclick="changeText()">Click me</button>


<script>
function changeText() {
let button = document.getElementById("myButton");
button.textContent = "Clicked!";
}
</script>
Now, let's understand how this code works:

When the HTML page loads, it displays a button with the text "Click me"
When a user clicks on the button, the “onclick” attribute specified in the HTML
tells the browser to call the “changeText” function
The “changeText” function is executed and selects the button element using its id
("myButton")
The “textContent” property of the button changes to "Clicked!"
As a result, when the button is clicked, its text changes from "Click me" to
"Clicked!"

It's a simple example of adding interactivity to a webpage using JavaScript.

onmouseover Event
The “onmouseover” event occurs when a user moves the mouse pointer over an HTML
element, such as an image, a button, or a hyperlink.

Here’s how the code that executes this event looks:

<img id="myImage" src="image.jpg" onmouseover="showMessage()">


<script>
function showMessage() {
alert("Mouse over the image!");
}
</script>
In this example, we have an HTML image element with the “id” attribute set to
"myImage."

It also has an “onmouseover” attribute specified, which indicates that when the
user hovers the mouse pointer over the image, the "showMessage ()" function should
be executed.

This function displays an alert dialog with the message "Mouse over the image!"

The “onmouseover” event is useful for adding interactivity to your web pages. Such
as providing tooltips, changing the appearance of elements, or triggering actions
when the mouse moves over specific areas of the page.

onkeyup Event
The “onkeyup” is an event that occurs when a user releases a key on their keyboard
after pressing it.

Here’s the code implementation for this event:

<input type="text" id="myInput" onkeyup="handleKeyUp()">


<script>
function handleKeyUp() {
let input = document.getElementById("myInput");
let userInput = input.value;
console.log("User input: " + userInput);
}
</script>
In this example, we have an HTML text input element <input> with the “id” attribute
set to "myInput."

It also has an “onkeyup” attribute specified, indicating that when a key is


released inside the input field, the "handleKeyUp()" function should be executed.

Then, when the user types or releases a key in the input field, the “handleKeyUp()”
function is called.

The function retrieves the input value from the text field and logs it to the
console.

This event is commonly used in forms and text input fields to respond to a user’s
input in real time.

It’s helpful for tasks like auto-suggestions and character counting, as it allows
you to capture users’ keyboard inputs as they type.

You might also like