JavaScript Intro

JavaScript is the programming language of the web.

All web browsers interpret JavaScript. Every web developer needs to learn JavaScript.

If you want your website to do something or respond to input, those instructions can be written in JavaScript.

JavaScript on w3schools.com

 

Console: Debugging and Error Messages

You can run JavaScript commands in the browser’s console (“F12” key or find in browser’s menu).

The console is where you can find JavaScript error messages. Notice that the line number is included in the error message to help you find the problem.

The console is like the Python window that we used in Canopy. You can check variable values and execute JavaScript commands from the console command line.

Script Tags

You can add JavaScript code into any HTML webpage.

JavaScript commands go inside <script> tags like so:

<body>
<p>This is an HTML webpage.</p>

<script>
console.log("Hello World!");
</script>

</body>

When you view that webpage, you won’t see “Hello World!” until you open the browser console.

Avoid Errors: Don’t Mix Up Languages

If you put HTML code inside <script> tags, your browser will think it’s bad JavaScript code.

Similarly, if you put JavaScript commands into an HTML file without putting <script> tags around it, the browser will think it’s HTML content and simply display the commands on your page.

JavaScript Syntax

JavaScript commands end with a semicolon ;

Curly braces { } are used to enclose code blocks.

Curly braces are used in all C family languages, such as C++, Java, and PHP.

See if you can spot every difference between the Python and JavaScript versions of a function:

Python  Comparison:

def hello():
    print("Hello!")
    print("This is a Python function.")

JavaScript version of this function:

function hello() {
    console.log("Hello!");
    console.log("This is a JavaScript function.");
}

Python uses tabs and line breaks to separate commands and code blocks. JavaScript uses curly braces and semicolons instead.

JavaScript doesn’t care how you arrange your tabs / indents, but you should be picky about tabs anyway so that your code’s visual organization is easy to understand on the screen. Tabs are a visual way to clearly show nesting structures in your code (code blocks inside of code blocks).