0% found this document useful (0 votes)
1 views11 pages

What is JavaScript

JavaScript is a programming language used for creating interactive and dynamic web pages, allowing for the manipulation of HTML and CSS. It supports various data types and structures, including variables, arrays, and functions, enabling developers to perform logic and handle user events. The document also covers JavaScript syntax, string methods, and examples of functions like Fibonacci and factorial.
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)
1 views11 pages

What is JavaScript

JavaScript is a programming language used for creating interactive and dynamic web pages, allowing for the manipulation of HTML and CSS. It supports various data types and structures, including variables, arrays, and functions, enabling developers to perform logic and handle user events. The document also covers JavaScript syntax, string methods, and examples of functions like Fibonacci and factorial.
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/ 11

What is JavaScript?

JavaScript is the Programming Language for the Web.

JavaScript can update and change both HTML and CSS.

JavaScript can calculate, manipulate and validate data.

HTML (HyperText Markup Language) is a markup language used to structure and


display content on the web, while JavaScript is a scripting language used to create
interactivity and dynamic effects on websites. HTML defines the content and
structure of a web page, while JavaScript allows for manipulation of the content and
the behaviour of the page.

HTML JavaScript
HTML (Hypertext Markup Language) is a JavaScript is a programming language used for
markup language used for creating static creating interactive and dynamic web pages.
web pages.
HTML is used to define the structure and JavaScript is used to add interactivity, modify
content of a web page. the content and styling of a web page, and
handle user events.
HTML is declarative and does not have JavaScript is a scripting language and can
the ability to perform logic or make perform logic, make decisions, and manipulate
decisions. the HTML DOM.
HTML consists of tags surrounded by JavaScript is written in a script and uses syntax
angle brackets. similar to other programming languages.
HTML documents are static and do not JavaScript can update and change the content
change unless modified by a developer. of an HTML document dynamically.
HTML is primarily used for structuring JavaScript is used for creating dynamic and
and displaying content. interactive experiences on the web.
HTML is not case sensitive. JavaScript is case sensitive.
HTML runs on the client side. JavaScript can run on both the client and server
side.

JavaScript Syntax

<script language=”javascript”>
Code….
</script>

Where to Put <script>


HEAD…..
Example:
<html>
<head>
<title> Your first JavaScript program </title>
<script language = "javascript">
document.write("Hello World!")
</script>
<head>
<body>

</body>
</html>
document.write????
document.write in JavaScript is a function that is used to display some strings in
the output of HTML web pages (Browser window).

Javascript can add html code……HOW…..


document.write("<h1>Hello World</h1>");

example
document.write("Hello World!");
document.write("<br>");
document.write("Have a nice day!");

JavaScript Variables
JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables:

Example
var x = 5;
var y = 6;
var z = x + y;

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11
JavaScript has only one type var

JavaScript has 8 Datatypes


String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
The Object Datatype
The object data type can contain both built-in objects, and user defined objects:
Built-in object types can be:
objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.
Examples
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).


Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}


function name(parameter1, parameter2, parameter3) {
// code to be executed
}

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":
Example

Calculate the product of two numbers, and return the result:


// Function is called, the return value will end up in x
let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

JavaScript Code for Fibonacci:


function fibonacciSeries(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib.slice(0, n);
}
// Example: Generate the first 10 numbers in the Fibonacci series
console.log(fibonacciSeries(10));

JavaScript Code for Factorial:

function factorial(number) {
if (number === 0 || number === 1) {
return 1;
}
else {
let result = 1;
let i = 2;
while (i <= number) {
result *= i;
i++;
}
return result;
}
}

JavaScript Arrays

An array is a special variable, which can hold more than one value:
var cars = ["Saab", "Volvo", "BMW",”Maruti”];

Creating an Array

Syntax:
var array_name = [item1, item2, ...];

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

Spaces and line breaks are not important. A declaration can span multiple lines:

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

Var cars = ["Saab", "Volvo", "BMW"];

You can also create an array, and then provide the elements:
Example
var cars = [];
cars[0]= "MAruti";
cars[1]= "Volvo";
cars[2]= "BMW";
Accessing Array Elements
var cars = ["Maruti", "Volvo", "BMW"];
var car = cars[0];
Access the Full Array
Using for….

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.


Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"

Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined

JavaScript String Methods

Strings are for storing text

Strings are written with quotes


var text = `He's often called "Johnny"`;

JavaScript String Length

The length property returns the length of a string:


Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Extracting String Characters

There are 4 methods for extracting string characters:


 The at(position) Method
 The charAt(position) Method
 The charCodeAt(position) Method
 Using property access [] like in arrays

JavaScript String charAt()

The charAt() method returns the character at a specified index (position) in a string:
Example
let text = "HELLO WORLD";
let char = text.charAt(6);

JavaScript String charCodeAt()

The charCodeAt() method returns the code of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);

JavaScript String at()


Examples

Get the third letter of name:


const name = "W3Schools";
let letter = name.at(2);

Get the third letter of name:


const name = "W3Schools";
let letter = name[2];

The at() method returns the character at a specified index (position) in a string.

The at() method is supported in all modern browsers since March 2022:
JavaScript String Search
JavaScript String indexOf()

The indexOf() method returns the index (position) of the first occurrence of a string in a string, or it
returns -1 if the string is not found:
Example
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
JavaScript String lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
Example
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");

Both indexOf(), and lastIndexOf() return -1 if the text is not found:


Example
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");
JavaScript String search()

The search() method searches a string for a string (or a regular expression) and returns the position of
the match:
Examples
let text = "Please locate where 'locate' occurs!";
text.search("locate");
JavaScript String match()

The match() method returns an array containing the results of matching a string against a string (or a
regular expression).
Examples

Perform a search for "ain":


let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");

JavaScript String slice()


<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>slice() extracts a part of a string and returns the extracted part:</p>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.slice(0, 5);

document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
The slice() Method

slice() extracts a part of a string and returns the extracted part:

Hello

<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>

<p>slice() extracts a part of a string and returns the extracted part:</p>

<p id="demo"></p>

<script>
let text = "Hello world!";
let result = text.slice(3);

document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>

The slice() Method

slice() extracts a part of a string and returns the extracted part:

lo world!

JavaScript String replace()

<html>

<body>

<h1>JavaScript Strings</h1>

<h2>The replace() Method</h2>

<p>replace() searches a string for a value,

and returns a new string with the specified value(s) replaced:</p>

<p id="demo">Visit Microsoft!</p>

<script>

let text = document.getElementById("demo").innerHTML;

document.getElementById("demo").innerHTML = text.replace("Microsoft", "W3Schools");

</script>

</body>

</html>

The replace() Method

replace() searches a string for a value, and returns a new string with the specified value(s) replaced:

Visit W3Schools!
JavaScript String replaceAll()

<html>

<body>

<h1>JavaScript Strings</h1>

<h2>The replaceAll() Method</h2>


<p>ES2021 intoduced the string method replaceAll().</p>

<p id="demo"></p>

<script>

let text = "I love cats. Cats are very easy to love. Cats are very popular."

text = text.replaceAll("Cats","Dogs");

text = text.replaceAll("cats","dogs");

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>
The replaceAll() Method

ES2021 intoduced the string method replaceAll().

I love dogs. Dogs are very easy to love. Dogs are very popular.

String indexOf()

<html>

<body>

<h1>JavaScript Strings</h1>

<h2>The indexOf() Method</h2>

<p>indexOf() returns the position of the first occurrence of a value in a string.</p>

<p>Find "welcome":</p>

<p id="demo"></p>

<script>

let text = "Hello world, welcome to the universe.";

let result = text.indexOf("welcome");

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>
The indexOf() Method

indexOf() returns the position of the first occurrence of a value in a string.

Find "welcome":

13

JavaScript String indexOf()

Examples
Search a string for "welcome":
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");

Search a string for "Welcome":


let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");

Find the first occurrence of "e":


let text = "Hello world, welcome to the universe.";
text.indexOf("e");

Find the first occurrence of "e", starting at position 5:


let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);

Find the first occurrence of "a":


let text = "Hello world, welcome to the universe.";
text.indexOf("a");

Example:
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>indexOf() returns the position of the first occurrence of a value in a string.</p>

<p>Find "a":</p>

<p id="demo"></p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.indexOf("a", 5);
</script>

</body>
</html>

indexOf() returns the position of the first occurrence of a value in a string.


Find "a":
-1

You might also like