DevNotes

DevNotes

@devnotes ·

JavaScript Part 1: Your first lines of code

HTML gives a page its content and CSS gives it a look. JavaScript makes it do things, like reacting to a click or loading new posts without a reload.

Try it in the console right now

On a laptop, open any website in Chrome, press F12 (or right-click and choose Inspect), and click the Console tab. Type this and press Enter:

JavaScript
2 + 2

You get 4. The console runs JavaScript instantly, so keep it open while you learn and test every idea there. The first time you paste code into it, Chrome may ask you to type allow pasting first. That's a safety check: type it once and carry on.

Add a script to your page

For real projects, write JavaScript in its own file, like script.js, and add it to your HTML:

HTML
<script src="script.js" defer></script>

Put that line in the <head>. defer tells the browser to download the script without holding up the page, and to run it once the HTML is ready. Without it, your code can run before the elements it's looking for even exist.

Then put this in script.js:

JavaScript
console.log("Hello from script.js");

Open the page and look at the console. console.log() prints whatever you give it. You'll use it constantly to check what your code is actually doing.

Variables

A variable is a name that holds a value, so you can use the value later.

JavaScript
let score = 0;score = score + 10;console.log(score); // 10
const city = "Pune";city = "Delhi"; // TypeError: Assignment to constant variable.
  • let makes a variable you can change later.
  • const makes one you can't point at a new value. Try, and you get an error.

Use const by default, and switch to let only when a value really needs to change. When you read code later, a const tells you at a glance that the value stays put.

You'll also see var in older code and tutorials. It has some confusing rules, so leave it out of new code.

Naming

Names can use letters, digits, _ and $, but can't start with a digit. They're case-sensitive, so score and Score are two different variables. The usual style is camelCase: totalPrice, isLoggedIn, userName.

Pick names that say what the value is. cartTotal says what it holds. x doesn't.

Comments

JavaScript
// A comment on one line
/* A comment   over several lines */

Reading errors

Type a name that doesn't exist:

JavaScript
console.log(scroe);

The console shows ReferenceError: scroe is not defined, plus the file and line number. Errors look scary at first, but they're the most useful thing JavaScript tells you. Read the message, go to the line, and most of the time the fix is a typo.

Try it

In the console, make a const called myName with your name, and a let called age with your age. Add 1 to age, then print both: console.log(myName, "will be", age).


Next: JavaScript Part 2: Values, types and operators

javascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.