0% found this document useful (0 votes)
43 views31 pages

01 IntroducingJavaScript

1. JavaScript was created in 1995 by Netscape to add interactivity to web pages and is now the dominant language for web content. 2. The document covers JavaScript data types, variables, arithmetic expressions, functions, and more basic concepts. 3. Functions are the main building blocks that allow code to be reused and are declared using the function keyword followed by a name, parameters in parentheses, and a code block.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
43 views31 pages

01 IntroducingJavaScript

1. JavaScript was created in 1995 by Netscape to add interactivity to web pages and is now the dominant language for web content. 2. The document covers JavaScript data types, variables, arithmetic expressions, functions, and more basic concepts. 3. Functions are the main building blocks that allow code to be reused and are declared using the function keyword followed by a name, parameters in parentheses, and a code block.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 31

CHAPTER 1

INTRODUCING JAVASCRIPT

1.1 Data and types


1.2 Numeric data
1.3 Variables
1.4 Functions
1.5 String data
1.6 Running JavaScript in the browser
Introducing JavaScript
• JavaScript was developed at the Netscape Communications Corporation
in 1995, reportedly by a single programmer in just 10 days. The
language, which was called Mocha at the time, was designed to serve as
a programming language that could be embedded in web pages viewed in
the browser.
• JavaScript has since become the dominant language for all interactive web
content and appears in some surveys as the most popular language in the
computing industry.
• JavaScript was initially created to “make web pages alive”. The programs
in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
• There are at least three great things about JavaScript:
• Full integration with HTML/CSS.
• Simple things are done simply.
• Support by all major browsers and enabled by default.
Data and Types
• The notion that data values come in many different forms gives rise to the
notion of a data type, which defines the common characteristics of data
values that have a particular form or purpose.
• In computer science, each data type is defined by a domain, which is the
set of values that belong to that type, and a set of operations, which
shows how the values in that domain can be manipulated.
• A value in JavaScript is always of a certain type. For example, a string or
a number or Boolean.
• We can put any type in a variable. For example, a variable can at one
moment be a string and then store a number:
Arithmetic Expressions
• Like most languages, JavaScript specifies computation in the form of an
arithmetic expression, which consists of terms joined together by
operators.
• Each term in an arithmetic expression is one of the following:
– An explicit numeric value, such as 2 or 3.14159265
– A variable name that serves as a placeholder for a value
– A function call that computes a value
– An expression enclosed in parentheses
• The operators are typically the familiar ones from arithmetic:

+ Addition
– Subtraction
* Multiplication
/ Division
% Remainder
The Remainder Operator
• The only arithmetic operator that has no direct counterpart in traditional
mathematics is %, which computes the remainder when the first divided
by the second:

14 % 5 returns 4
14 % 7 returns 0
7 % 14 returns 7

• The result of the % operator make intuitive sense only if both operands are
positive integers. The examples in the book do not depend on knowing
how % works with negative numbers or numbers that have fractional
parts.
• The remainder operator turns out to be useful in a surprising number of
programming applications and is well worth a bit of study.
Precedence
• If an expression contains more than one operator, JavaScript
uses precedence rules to determine the evaluation order. The
arithmetic operators have the following relative precedence:
highest
unary -

* / %

+ -
lowest
Thus, JavaScript evaluates unary – operators first, then the
operators *, /, and %, and then the operators + and -.
• Precedence applies only when two operands compete for the
same operator. If the operators are independent, JavaScript
evaluates expressions from left to right. Parentheses may be
used to change the order of operations.
Variables
• The simplest terms that appear in expressions are constant
literals and variables. A variable is a placeholder for a value
that can be updated as the program runs.
• A variable in JavaScript is most easily envisioned as a box
capable of storing a value
answer
42

• Each variable has the following attributes:


– A name, which enables you to tell the variables apart.
– A value, which represents the current contents of the variable.
• The name of a variable is fixed; the value changes whenever
you assign a new value to the variable.
Variable Declarations
• In JavaScript, you must declare a variable before you can use
it. The declaration establishes the name of the variable and,
in most cases, specifies the initial value as well.
• The most common form of a variable declaration is

let name = value;

where name is an identifier that indicates the name of the


variable, and value is an expression specifying the initial
value.
• Most declarations appear as statements in the body of a
function definition. Variables declared in this way are called
local variables and are accessible only inside that function.
Variable Declarations
• The
statement below creates (in other words: declares) a variable with the
name “message”:

• Now, we can put some data into it by using the assignment operator =:
Constant Declarations
• It is often useful to give names to values that you don’t intend
to change while the program runs. Such values are called
constants.
• A constant declaration is similar to a variable declaration:

const name = value;

As before, name is an identifier that indicates the name of the


constant, and value is an expression specifying its value.
Constant Declarations
• To declare a constant (unchanging) variable, use const instead of let:

• Variables
declared using const are called “constants”. They cannot be
reassigned. An attempt to do so would cause an error:
Naming Conventions
• In JavaScript, all names must conform to the syntactic rules
for identifiers, which means that the first character must be a
letter and the remaining characters must be letters, digits, or
the underscore character.
• Beyond these rules that apply to all JavaScript names, there
are several conventions that programmers use to make their
identifier names easier to recognize:
– Variable names and function names begin with a lowercase
letter. If a name consists of more than one word, the first letter
in each word is capitalized, as in numberOfStudents. This
convention is called camel case.
– Class names and program names begin with an uppercase letter.
– Constant names are written entirely in uppercase and use the
underscore character to separate words, as in MAX_HEADROOM.
Assignment Statements
• You can change the value of a variable in your program by
using an assignment statement, which has the general form:

variable = expression;

• The effect of an assignment statement is to compute the value


of the expression on the right side of the equal sign and assign
that value to the variable that appears on the left. Thus, the
assignment statement
total = total + value;
adds together the current values of the variables total and
value and then stores that sum back in the variable total.
• When you assign a new value to a variable, the old value of
that variable is lost.
Shorthand Assignments
• Statements such as
total = total + value;
are so common that JavaScript allows the following shorthand:
total += value;

• The general form of a shorthand assignment is

variable op= expression;

where op is any of JavaScript’s binary operators. The effect


of this statement is the same as
variable = variable op (expression);
Increment and Decrement Operators
• Another important shorthand that appears frequently in
JavaScript programs is the increment operator, which is most
commonly written immediately after a variable, like this:
x++;

The effect of this statement is to add one to the value of x,


which means that this statement is equivalent to
x += 1;
or
x = x + 1;

• The -- operator (which is called the decrement operator) is


similar but subtracts one instead of adding one.
Functions
• Functions are the main “building blocks” of the program. They allow the
code to be called many times without repetition.
• To create a function we can use a function declaration. It looks like this:

• The function keyword goes first, then goes the name of the function, then


a list of parameters between the parentheses (comma-separated, empty in
the example above) and finally the code of the function, also named “the
function body”, between curly braces.
Example of Functions
• Our new function can be called by its name: showMessage().
For instance:

• Thecall showMessage() executes the code of the function. Here we will see the


message two times.
Writing JavaScript Functions
• The general form of a function definition is

function name(parameter list) {


statements in the function body
}

where name is the name of the function, and parameter list is


a list of variables used to hold the values of each argument.
• You can return a value from a function by including a return
statement, which is usually written as

return expression;

where expression is an expression that specifies the value you


want to return.
Examples of Simple Functions
• The following function converts Fahrenheit temperatures to
their Celsius equivalent:

function fahrenheitToCelsius(f) {
return 5 / 9 * (f – 32);
}

• The following function computes the area of a triangle from


its base and height:

function triangleArea(base, height) {


return (base * height) / 2;
}
Naming a Functions
• Functions are actions. So their name is usually a verb.
• For instance, functions that start with "show" usually show something.
• Function starting with…
•"get…" – return a value,
•"calc…" – calculate something,
•"create…" – create something,
•"check…" – check something and return a boolean, etc.
The String Type
• One of the most important data types in any programming
language is the string type.
• The domain of the string type is all sequences of characters.
In JavaScript, you create a string simply by including that
sequence of characters inside quotation marks, as in "Eric".
• All values—including numbers, strings, graphical objects,
and values of many other types—can be assigned to variables,
passed as arguments to functions, and returned as results.
The String Type
• A string in JavaScript must be surrounded by quotes.

• In JavaScript, there are 3 types of quotes.

1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
Example of String Type
• Double and single quotes are “simple” quotes. There’s practically no
difference between them in JavaScript.
• Backticks are “extended functionality” quotes. They allow us to embed
variables and expressions into a string by wrapping them in ${…}, for
example:
Concatenation
• One of the most useful operations available for strings is
concatenation, which consists of combining two strings end
to end with no intervening characters.
• Concatenation is built into JavaScript using the + operator.
For example, the expression "ABC" + "DEF" returns the string
"ABCDEF".
• If you use + with numeric operands, it signifies addition. If at
least one of its operands is a string, JavaScript interprets + as
concatenation. It automatically converts the other operand to
a string and concatenates the two strings, so that
"Catch" + -22 "Catch-22"
The “Hello World” Program
• In 1978, Brian Kernighan and
Dennis Ritchie wrote a reference
manual for the C programming 1.1 Getting Started

language, one of the forerunners of The only way to learn a new programming
language is to write programs in it. The first
JavaScript. program to write is the same for all languages:

Print the words


• On the first page of their book, the hello, world

authors suggest that the first step in This is the big hurdle; to leap over it you have to
be able to create the program text somewhere,
learning any language is to write a compile it, load it, run it, and find out where your
output went. With these mechanical details
simple program that prints the mastered, everything else is comparatively easy.

words “hello, world” on the display. In C, the program to print “hello, world” is

That advice remains sound today. #include <stdio.h>

main() {
• The next few slides show you how }
printf("hello, world");

to write the “Hello World” program


in JavaScript.
The Web’s Client-Server Model
client browser web server

http://mypage/index.html

index.html O

1. The user starts a web browser.


2. The user requests a web page.
3. The browser sends a network request for the page.
4. The server sends back a text file containing the HTML.
5. The browser interprets the HTML and renders the page image.
The Three Central Web Technologies
• Modern web pages depend on three technological tools:
HTML (Hypertext Markup Language), CSS (Cascading Style
Sheets), and JavaScript.
• These tools are used to control different aspects of the page:
– HTML is used to specify content and structure.
– CSS is used to control appearance and formatting.
– JavaScript is used to animate the page.
The Structure of an HTML File
• An HTML file consists of the text to be displayed on the
page, interspersed with various commands enclosed in angle
brackets, which are known as tags.
• HTML tags usually occur in pairs. The opening tag begins
with the name of the tag. The corresponding closing tag has
the same name preceded by a slash. The effect of the tag
applies to everything between the opening and closing tag.
• The only HTML tags you will need to use for most of the
course appear in the template on the next page, which
describes the structure of the HTML index file, which is
conventionally called index.html.
Standard index.html Pattern
• The following components of index.html are standardized:
– Every file begins with a <!DOCTYPE html> tag
– The entire content is enclosed in <html> and </html> tags.
– The file begins with a <head> section that specifies the title
and JavaScript files to load.
– The file includes a <body> section that specifies the page.
Creating the HTML File (Version 1)
• A simple HTML file that loads the HelloWorld.js program
looks like this:
<!DOCTYPE html>
<html>
<head>
<title>HelloWorld</title>
<script type="text/javascript" src="HelloWorld.js"></script>
</head>
<body onload="HelloWorld()">
</body>
</html>

• This file asks the browser to load the file HelloWorld.js and
then call the function HelloWorld once the page is loaded.
Creating the HTML File (Version 2)
• The output from the console log appears in different places in
different browsers and usually requires the user to take some
explicit action before it is visible.
• To make the console log easier to find, we have provided a
library called JSConsole.js that redirects the console log to
an area of the web page marked with the id JSConsole.
<!DOCTYPE html>
<html>
<head>
<title>HelloWorld</title>
<script type="text/javascript" src="JSConsole.js"></script>
<script type="text/javascript" src="HelloWorld.js"></script>
</head>
<body onload="HelloWorld()">
</body>
</html>

You might also like