Learning coding means GreatToCode Be more than a Coder ! Greattocode , Join GreatToCode Community,1000+ Students Trusted On Us .If You want to learn coding, Then GreatToCode Help You.No matter what It Takes !


CODE YOUR WAY TO A MORE FULFILLING And HIGHER PAYING CAREER IN TECH, START CODING FOR FREE Camp With GreatToCode - Join the Thousands learning to code with GreatToCode
Interactive online coding classes for at-home learning with GreatToCode . Try ₹Free Per Month Coding Classes With The Top Teachers . JavaScript Tutorial

JavaScript Tutorial

 

Examples in Each Chapter

With our "Try it Yourself" editor, you can edit the source code and view the result.

Example

My First JavaScript

Try it Yourself »


Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign .


Learn by Examples

Examples are better than 1000 words. Examples are often easier to understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

If you try all the examples, you will learn a lot about JavaScript, in a very short time!

JavaScript Examples »

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

   3. JavaScript to program the behavior of web pages



In this tutorial, the learning speed is your choice.


Everything is up to you.


If you are struggling, take a break, or re-read the material.


Always make sure you understand all the "Try-it-Yourself" examples.


The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code !



JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":

Example

document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »

JavaScript accepts both double and single quotes:

Example

document.getElementById('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

The Light Bulb

  

Try it Yourself »

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example

document.getElementById("demo").style.fontSize = "35px";
Try it Yourself »

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

Example

document.getElementById("demo").style.display = "none";
Try it Yourself »

JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by changing the display style:

Example

document.getElementById("demo").style.display = "block";
Try it Yourself »

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

Try it Yourself »

Old JavaScript examples may use a type attribute: <script type="text/javascript">.
The type attribute is not required. JavaScript is the default scripting language in HTML.


JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

You will learn much more about functions and events in later chapters.


JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.


JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Try it Yourself »

JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

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

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>
Try it Yourself »

Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

Example

<script src="myScript.js"></script>
Try it Yourself »

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.


External JavaScript Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

To add several script files to one page  - use several script tags:

Example

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

External References

An external script can be referenced in 3 different ways:

  • With a full URL (a full web address)
  • With a file path (like /js/)
  • Without any path

This example uses a full URL to link to myScript.js:

Example

<script src="https://www.w3schools.com/js/myScript.js"></script>

Try it Yourself »

This example uses a file path to link to myScript.js:

Example

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

Try it Yourself »

This example uses no path to link to myScript.js:

Example

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

Try it Yourself »

JavaScript Display Possibilities



JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

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

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Try it Yourself »

Changing the innerHTML property of an HTML element is a common way to display data in HTML.


Using document.write()

For testing purposes, it is convenient to use document.write():

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
Try it Yourself »

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
Try it Yourself »

Using window.alert()

You can use an alert box to display data:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Try it Yourself »

You can skip the window keyword.

In JavaScript, the window object is the global scope object, that means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>
Try it Yourself »

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

You will learn more about debugging in a later chapter.

Example

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
Try it Yourself »

JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print the content of the current window.

Example

<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>
Try it Yourself »

Example

let x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4
Try it Yourself »

JavaScript Programs

computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.


JavaScript Statements

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs (and JavaScript statements) are often called JavaScript code.


Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

Examples

let a, b, c;  // Declare 3 variables
a = 5;        // Assign the value 5 to a
b = 6;        // Assign the value 6 to b
c = a + b;    // Assign the sum of a and b to c
Try it Yourself »

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;
Try it Yourself »

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

The following lines are equivalent:

let person = "Hege";
let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:

Example

function myFunction() {
  document.getElementById("demo1").innerHTML = "Hello Dolly!";
  document.getElementById("demo2").innerHTML = "How are you?";
}
Try it Yourself »

In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.


JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:

KeywordDescription
varDeclares a variable
letDeclares a block variable
constDeclares a block constant
ifMarks a block of statements to be executed on a condition
switchMarks a block of statements to be executed in different cases
forMarks a block of statements to be executed in a loop
functionDeclares a function
returnExits a function
tryImplements error handling to a block of statementsJavaScript syntax is the set of rules, how JavaScript programs are constructed:
// How to create variables:
var x;
let y;

// How to use variables:
x = 5;
y = 6;
let z = x + y;

JavaScript Values

The JavaScript syntax defines two types of values:

  • Fixed values
  • Variable values

Fixed values are called Literals.

Variable values are called Variables.


JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'
Try it Yourself »

JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords varlet 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;
Try it Yourself »

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:

(5 + 6) * 10
Try it Yourself »

JavaScript uses an assignment operator ( = ) to assign values to variables:

let x, y;
x = 5;
y = 6;
Try it Yourself »

JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

Expressions can also contain variable values:

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"
Try it Yourself »

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »

The var keyword also tells the browser to create variables:

var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »

In these examples, using var or let will produce the same result.

You will learn more about var and let later in this tutorial.


JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

let x = 5;   // I will be executed

// x = 6;   I will NOT be executed
Try it Yourself »

You will learn more about comments in a later chapter.


JavaScript Identifiers / Names

Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

  • A letter (A-Z or a-z)
  • A dollar sign ($)
  • Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note

Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.


JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive

The variables lastName and lastname, are two different variables:

let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
Try it Yourself »

JavaScript does not interpret LET or Let as the keyword let.


JavaScript and Camel Case

Historically, programmers have used different ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. They are reserved for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.


JavaScript Character Set

JavaScript uses the Unicode character set.


Post a Comment

0 Comments

•Give The opportunity to your child with GreatToCode Kid's • Online Coding Classes for Your Kid • Introduce Your kid To the world's of coding
•Fuel You Career with our 100+ Hiring Partners, Advance Your Career in Tech with GreatToCode. •Join The Largest Tech and coding Community and Fast Forward Your career with GreatToCode. •10000+ Learner's+ 90 % placement Guarantee. • Learning Coding is Better with the GreatToCode community .
•Greattocode Kid's •GreatToCode Career •GreatToCode Interview •GreatToCode Professional •GreatToCode for schools •GreatToCode For colleges •GreatToCods For Businesses.
Are you ready to join the millions of people learning to code? GreatToCode Pass is your one-stop-shop to get access to 1000+ courses, top-notch support, and successful job placement. What are you waiting for? Sign up now and get your future in motion with GreatToCode Pass.