Lecture8-Intro To Javascript
Lecture8-Intro To Javascript
Javascript
"I was under marketing orders to make it look like Java but not make it too big for its
britches ... [it] needed to be a silly little brother language." (source)
JavaScript
in the browser
Code in web pages
HTML can embed JavaScript files into the web page via the <script> tag.
<!DOCTYPE html>
<html>
<head>
<title>CS 193X</title>
<link rel="stylesheet" href="style.css" />
<script src="filename.js"></script>
</head>
<body>
... contents of the page...
</body>
</html>
console.log
You can print log messages in JavaScript by calling console.log():
script.js
console.log('Hello, world!');
And the server responds with the JavaScript file, just like it
would with a CSS file or an image...
<head>
<title>CS 193X</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
console.log('Hello, world!');
(Note that this is slightly different than being "interpreted": see just-in-time
(JIT) compilation)
first-js.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>First JS Example</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
script.js
console.log('Hello, world!');
Hey, nothing happened!
Right-click (or control-click on Mac) and choose "Inspect"
Click "Console" tab
The "Console" tab is also a REPL, or an interactive language
shell, so you can type in JavaScript expressions, etc. to test
out the language.
We will be using this throughout the quarter!
JavaScript
language features
Same as Java/C++/C-style langs
for-loops:
for (let i = 0; i < 5; i++) { … }
while-loops:
while (notFinished) { … }
comments:
// comment or /* comment */
conditionals (if statements):
if (...) {
...
} else {
...
}
Functions
One way of defining a JavaScript function is with the following syntax:
function name() {
statement;
statement;
...
}
script.js
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
hello();
hello();
Console output
script.js
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
hello();
hello();
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
Caveats:
- There are other ways to define
functions that do not get hoisted;
- Try not to rely on hoisting when
coding. It gets bad.
Console output