0% found this document useful (0 votes)
7 views16 pages

Lec.06 JavaScript

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

Lec.06 JavaScript

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

Hello, JavaScript!

The “script” tag


JavaScript programs can be inserted almost anywhere into an HTML
document using the <script> tag.

For instance:

<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>

<script>
alert( 'Hello, world!' );
</script>

<p>...After the script.</p>


</body>
</html>

1
External scripts
If we have a lot of JavaScript code, we can put it into a separate file.
Script files are attached to HTML with the src attribute:

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

Here, /path/to/script.js is an absolute path to the script from the site root.
One can also provide a relative path from the current page. For instance,
src="script.js", just like src="./script.js", would mean a file "script.js" in the
current folder.

We can give a full URL as well. For instance:

<script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></
script>

To attach several scripts, use multiple tags:

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

2
Summary
●​ We can use a <script> tag to add JavaScript code to a page.
●​ The type and language attributes are not required.
●​ A script in an external file can be inserted with <script
src="path/to/script.js"></script>.

3
Code structure

Statements
Statements are syntax constructs and commands that perform actions.

We’ve already seen a statement, alert('Hello, world!'), which shows the


message “Hello, world!”.

We can have as many statements in our code as we want. Statements can


be separated with a semicolon.

4
For example, here we split “Hello World” into two alerts:

alert('Hello'); alert('World');

Usually, statements are written on separate lines to make the code more
readable:

alert('Hello');
alert('World');

Semicolons
A semicolon may be omitted in most cases when a line break exists.
This would also work:

alert('Hello')

alert('World')

Here, JavaScript interprets the line break as an “implicit” semicolon. This is


called an automatic semicolon insertion.

5
Comments

One-line comments start with two forward slash characters //.

// This comment occupies a line of its own


alert('Hello');

alert('World'); // This comment follows the statement

Multiline comments start with a forward slash and an asterisk /* and end
with an asterisk and a forward slash */.

/* An example with two messages.


This is a multiline comment.
*/
alert('Hello');
alert('World');

6
Variables
Most of the time, a JavaScript application needs to work with information.
Here are two examples:
1.​ An online shop – the information might include goods being sold and
a shopping cart.
2.​ A chat application – the information might include users, messages,
and much more.
Variables are used to store this information.

A variable
A variable is a “named storage” for data. We can use variables to store
goodies, visitors, and other data.

To create a variable in JavaScript, use the let keyword.

The statement below creates (in other words: declares) a variable with the
name “message”:

let message;

Now, we can put some data into it by using the assignment operator =:

let message;

7
message = 'Hello'; // store the string 'Hello' in the variable named
message

The string is now saved into the memory area associated with the variable.
We can access it using the variable name:

let message;
message = 'Hello!';

alert(message); // shows the variable content


To be concise, we can combine the variable declaration and assignment
into a single line:

let message = 'Hello!'; // define the variable and assign the value

alert(message); // Hello!

We can also declare multiple variables in one line:


let user = 'John', age = 25, message = 'Hello';

Variable naming
There are two limitations on variable names in JavaScript:
1.​ The name must contain only letters, digits, or the symbols $ and _.
2.​ The first character must not be a digit.

8
Examples of valid names:

let userName;
let test123;

Constants
To declare a constant (unchanging) variable, use const instead of let:
const myBirthday = '18.04.1982';

Uppercase constants

There is a widespread practice to use constants as aliases for


difficult-to-remember values that are known before execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in so-called “web”


(hexadecimal) format:

const COLOR_RED = "#F00";


const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";

9
// ...when we need to pick a color
let color = COLOR_ORANGE;
alert(color); // #FF7F00

Name things right

Some good-to-follow rules are:


●​ Use human-readable names like userName or shoppingCart.
●​ Stay away from abbreviations or short names like a, b, and c, unless
you know what you’re doing.
●​ Make names maximally descriptive and concise. Examples of bad
names are data and value. Such names say nothing. It’s only okay to
use them if the context of the code makes it exceptionally obvious
which data or value the variable is referencing.
●​ Agree on terms within your team and in your mind. If a site visitor is
called a “user” then we should name related variables currentUser or
newUser instead of currentVisitor or newManInTown.

10
Summary

We can declare variables to store data by using the var, let, or const
keywords.
●​ let – is a modern variable declaration.
●​ var – is an old-school variable declaration. Normally we don’t use it
at all, but we’ll cover subtle differences from let in the chapter The
old "var", just in case you need them.
●​ const – is like let, but the value of the variable can’t be changed.
Variables should be named in a way that allows us to easily understand
what’s inside them.

11
Data types
A value in JavaScript is always of a certain type. For example, a string or a
number.

There are eight basic data types in JavaScript. For example, a variable can
at one moment be a string and then store a number:

let message = "hello";


message = 123456;

There are 8 basic data types in JavaScript.


❖​Seven primitive data types:
➢​number for numbers of any kind: integer or floating-point,
integers are limited by ±(253-1).
➢​bigint for integer numbers of arbitrary length.
➢​string for strings. A string may have zero or more characters,
there’s no separate single-character type.
➢​boolean for true/false.
➢​null for unknown values – a standalone type that has a single
value null.
➢​undefined for unassigned values – a standalone type that has a
single value undefined.
➢​symbol for unique identifiers.
❖​And one non-primitive data type:

12
➢​object for more complex data structures.

The typeof operator allows us to see which type is stored in a variable.


●​ Usually used as typeof x, but typeof(x) is also possible.
●​ Returns a string with the name of the type, like "string".
●​ For null returns "object" – this is an error in the language, it’s not
actually an object.

typeof true // "boolean"

13
Interaction: alert, prompt, confirm
As we’ll be using the browser as our demo environment, let’s see a couple
of functions to interact with the user: alert, prompt and confirm.

alert
This one we’ve seen already. It shows a message and waits for the user to
press “OK”.
For example:
alert("Hello");
The mini-window with the message is called a modal window. The word
“modal” means that the visitor can’t interact with the rest of the page,
press other buttons, etc, until they have dealt with the window. In this case
– until they press “OK”.

prompt
The function prompt accepts two arguments:
result = prompt(title, [default]);
It shows a modal window with a text message, an input field for the visitor,
and the buttons OK/Cancel.
title
The text to show the visitor.
default
An optional second parameter, the initial value for the input field.

14
confirm
The syntax:

result = confirm(question);

The function confirm shows a modal window with a question and two
buttons: OK and Cancel.
The result is true if OK is pressed and false otherwise.
For example:

let isBoss = confirm("Are you the boss?");

alert( isBoss ); // true if OK is pressed

15
References:
https://javascript.info/
Read An introduction and JavaScript Fundamentals chapters

16

You might also like