Now that we know how to specify grammars for well-balanced expressions
and arithmetic and well-balanced webpage tags in HTML,
we're going to return our attention to JavaScript.
JavaScript is actually very similar to Python.
Just like I showed you a formal grammar for HTML,
we're going to work our way up to seeing a formal grammar for JavaScript.
But before we get there, I just want to make sure
that we really understand how JavaScript programs are interpreted.
I'm going to show you a few more in Python and in JavaScript for comparison.
Over here on the left, I have a Python function
that computes the absolute value of its integer argument.
If you give me a negative number, like -5, I will return positive 5.
If you give me a positive number, like +9 million, I will return 9 million.
The return value of this function is always either a zero a positive number.
Now I'm going to write the same thing in JavaScript
to provide for a comparison.
Everything I've drawn in blue is a special keyword or punctuation mark used by the language.
For example, to define a function in Python we use "def."
In JavaScript, we write out the word function, but then it's still our choice what to call it--
I'm called it "absval" in both cases--
and how many parameters it should receive and what they're names are.
In both cases, we have one parameter named x.
In Python we use colons and tabbing to tell what the body of a function is,
what the then branch for an if is, what the else branch for an if is.
In JavaScript, we use curly braces and closing curly braces
to denote this sort of lexical or syntactic scope.
This is sort of curly brace 1, and it matches up with closed curly brace 1 over here,
2 matches up with 2, and 3 matches up with 3.
But in general the logical structure, the flow or the meaning, is the same.
In both cases we check to see if x is less than 0, and we return 0 minus x in that case,
or just x alone in the other case.
One of the most important operations in any language is printing out information,
displaying it to the screen so that we can see the result of computation
or just to help us debug.
In Python we use the print procedure.
We pass it a bunch of strings.
Here I'm adding together the strings "hello" and exclamation mart
to make a very enthusiastic greet--"hello!"
Over here on the right, I'm showing the same thing in JavaScript.
The equivalent of "print" is "document.write" or perhaps just "write."
In this class, we'll almost always abbreviate it down to just "write" to save space.
If you're familiar with object-oriented programming, which is not required for this class,
you might guess what the dot is about.
We might talk more about that later.
One of the key differences, though, is that all of our JavaScript functions have to have
these open and close parentheses like a mathematical function
has parentheses around its argument.
バランスのとれた式や対になるHTMLタグの
文法の指定方法を学びました
JavaScriptに話を戻しましょう
JavaScriptはPythonに非常によく似ています
HTMLの形式文法をお見せしたのと同じように
JavaScriptの形式文法も見ていきます
その前に確認しておくことがあります
JavaScriptプログラムが
どのように解釈されるかを理解しましょう
PythonとJavaScriptとの比較でお見せします
Pythonの関数を書きました
これは整数の引数の絶対値を計算しています
-5のような負の数を与えると5を返します
900万という正の数を与えると900万を返します
この関数の戻り値は
常に0か正の数のどちらかになります
ではJavaScriptでも同じものを書きます
比較します
青字で書いたものはすべてその言語で使われる
特殊なキーワードや句読点です
例えばPythonで関数を定義する時は
defを使います
JavaScriptでは単語のfunctionを書きます
両方に共通するのは
absvalの呼び出しです
受け取るパラメータの数とその名前も同じです
どちらもxという名前のパラメータを持ちます
Pythonではコロンやタブを使って関数の本体や
分岐のifやelseを表します
JavaScriptでは{}を使い
字句や構文の範囲を表します
{の1は }の1と対になります
2番目 3番目もそれぞれ対になります
しかし概ね 論理構造、流れ、意味は同じです
どちらもでxが0未満である場合は0-xを返します
0より大きい場合はxを返します
どの言語においても出力処理は重要です
画面上に表示することです 処理結果を見たり
デバッグしたりするのに使います
Pythonではprintプロシージャを使います
文字列をここに渡します
hello!と感嘆符をつけました
熱烈な挨拶にしました こんにちは!
右側のJavaScriptにも同じ処理を記述します
printに相当するのは
document.writeまたはwriteです
余白を節約するためにwriteを書きます
この講義の範囲ではありませんが
オブジェクト指向プログラミングに詳しければ
ドットが何を意味するか推測するかもしれません
これについては後ほどお話しします
大きな違いはJavaScript関数ではすべて
数式のように丸括弧を記述する必要があります
数学の関数が引数を持つ際に
丸括弧を使うのと同じです
Agora que sabemos como especificar gramáticas para expressões balanceadas,
expressões aritméticas e tags de HTML balanceadas,
vamos voltar nossa atenção para JavaScript.
JavaScript é muito semelhante a Python.
Assim como eu mostrei a você uma gramática formal para HTML,
vamos ver agora uma gramática formal para JavaScript.
Mas, antes disso, quero ter certeza
de que você entende como programas Javascript são interpretados.
Vou mostrar para você um pouco mais de Python e JavaScript, apenas para comparação.
Aqui, à esquerda, temos uma função Python
que computa o valor absoluto do seu argumento inteiro.
Se você passa um número negativo, como -5, ela retorna o valor positivo 5.
Se você passa um número positivo, como 9000000, ela retorna 9000000.
O valor de retorno dessa função é sempre zero ou um número positivo.
Vou escrever a mesma coisa em JavaScript,
para fins de comparação.
Tudo que eu escevi em azul é uma palavra reservada ou símbolo de pontuação usado na linguagem.
Por exemplo, para definir uma função em Python, usamos `def'.
Em JavaScript, escrevemos a palavra `function', mas ainda é nossa escolha como chamá-la --
estou chamando a função de `absval' em ambos os casos --
e também quantos parâmetros ela deve ter e quais são os seus nomes --
em ambos os casos, temos 1 parâmetro, chamado `x'.
Em Python, usamos `:' e tabulação para indicar o que é o corpo da função,
e qual é a parte correspondente ao `then' e ao `else' de um comando `if'.
Em JavaScript usamos `{' e `}'
para indicar esse tipo de escopo léxico.
Este é um tipo de `{' (1), e ele casa com este `}' (1) aqui;
(2) casa com (2) e (3) casa com (3).
Mas, em geral, a estrutura lógica, o significado, é o mesmo.
Em ambos os casos, verificamos se x < 0 e retornamos 0-x, neste caso,
ou simplesmente x caso contrário.
Uma das operações mais importantes em qualquer linguagem de programação é imprimir uma informação,
exibir uma informação na tela, para que possamos ver o resuldado da computação,
ou simplesmente para nos ajudar a testar o programa.
Em Python, usamos esta função print,
passando para ela alguns strings.
Aqui estou concatenando os strings `hello' e `!'
para cumprimetar com estusiasmo -- "hello!".
Aqui à direita, estou mostrando a mesma coisa em JavaScript.
O equivalente a print é document.write, ou siamplesmente write.
Neste curso, vamos quase sempre abreviar para write, para economizar espaço.
Se você tem familiaridade com programação orientada a objetos, o que não é necessário neste curso,
você deve saber o que este ponto significa.
Podemos falar mais sobre isso depois.
Uma das diferenças fundamentais, entretanto, é que toda aplicação de uma função JavaScript deve ter
estes `(' e `)', como uma função matemática
tem parênteses em torno de seus argumentos.