Why won't my rectangle move when I press the key? - javascript

So I'm trying to make a snake game from scratch a practice for making games in javascript. I've made the square inside of my canvas, and now I'm trying to make it move. This is the code I've made for it.
<!DOCTYPE html>
<html>
<body>
<canvas id = "gameCanvas" width="700" height="600" style="border:4px solid black; background-color: yellow"></canvas>
<script type = "text/javascript">
var myCanvas = document.getElementById("gameCanvas");
var ctx = myCanvas.getContext("2d");
this.x = 0;
this.y = 0;
var snake = ctx.fillRect(this.x,this.y,10,10);
myMovement = function(){
var moveUp = event.keyCode;
if(moveUp == 39){
snake = ctx.fillRect(this.x + 1, this.y,10,10);
}
}
</script>
</body>
</html>
Unfortunately, when I press the button, nothing happens. What's wrong with my code.

There are a few problems with your code.
You are using this in a place where it is going to reference the global object (window in this case).
Your myMovement function isn't attached to anything, meaning it isn't setup as a event listener which is needed for it to be called when a key is pressed
Even if your myMovement was setup it didn't have the event object defined as a parameter so your function would have errored out as there wouldn't have been an event object to access
For 1 if you are meaning to you keep track of the x,y you can place them in an object and access them from there:
var rect={
x:0,
y:0
};
//then when needing to use them access them like rect.x, rect.y
//also fillRect doesn't return anything so no need for "var snake = "
ctx.fillRect(rect.x, rect.y, 10, 10);
For 2 and 3 you can use the various key* events for your function. You can attach the function by using addEventListener. Finally define an event parameter for your function so that you actually have an event object to use:
function myMovement(event) {
var moveUp = event.keyCode;
if(moveUp == 39){
//++rect.x adds one and assigns the new value to rect.x
//and again fillRect doesn't return a value so no need for "snake ="
ctx.fillRect(++rect.x, rect.y,10,10);
}
}
window.addEventListner("keydown",myMovement);
Demo
var myCanvas = document.getElementById("gameCanvas");
var ctx = myCanvas.getContext("2d");
var rect = {
x: 0,
y: 0
};
ctx.fillRect(rect.x, rect.y, 10, 10);
window.onkeydown = function(event) {
var moveUp = event.keyCode;
if (moveUp == 39) {
//erase last fill
ctx.clearRect(rect.x, rect.y, 10, 10);
ctx.fillRect(++rect.x, rect.y, 10, 10);
}
}
<canvas id="gameCanvas" width="100%" height="100%" style="border:4px solid black; background-color: yellow"></canvas>

problem findings:
myMovement = function(){
var moveUp = event.keyCode;
if(moveUp == 39){
snake = ctx.fillRect(this.x + 1, this.y,10,10);
}
}
when myMovement will fire it does not know the code, and
//x value just add 1 with previous but not increment gradually, so it should be this.x += 1
ctx.fillRect(this.x + 1, this.y,10,10);
Solution:
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 39) {
snake = ctx.fillRect(this.x += 1, this.y,10,10);
}
}
you can see here for the keyboard keys value
The onkeyup event occurs when the user releases a key (on the
keyboard).
Actually there are 3 different options to fire key event
onkeydown
onkeypress
onkeyup

Related

Block in canvas dissapeared for one frame

I'm trying to build Snake from scratch using Javascript. But when I use the arrow keys to get it from 1 part of the canvas to the other part of the canvas it dissapears for 1 frame, how to resolve this? You can try it on: https://annedegraaff.nl/snake/
<canvas id="snake" width="400" height="400">
</html>
<script>
var canvas;
var canvasContext;
var ball1X = 12.5;
var ball1Y = 12.5;
window.onload = function() {
canvas = document.getElementById('snake');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 60;
setInterval(function() {
draw();
move();
}, 1000/framesPerSecond);
}
function move() {
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (ball1X < 12.5) {
ball1X += 395;
}else if (ball1X > 385) {
ball1X -= 395;
}
if (key == 39) {
ball1X += 10;
}else if (key == 37) {
ball1X -= 10;
}else if (key == 40) {
ball1Y += 10;
}else if (key == 38) {
ball1Y -= 10;
}
}
}
function draw() {
canvasContext.fillStyle = 'green';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'black';
canvasContext.fillRect(ball1X,ball1Y,10,10);
}
</script>
Logic error in keyEvent handler
Though not directly evident where the problem is in the given code I am assuming it is the test for edges in the keydown handler. There are also other ting being done incorrectly that will present additional problems and difficulties as you develop the game.
Your bug
In your keyboard function you test if the ball is close to the edge and if so you move it to the other size. Looks like you move it too far and thus can not be seen.
The following is a quick fix. Move the test to after the ball has been moved and make sure the the move to the other side does not put it too far so that it is moved again on the next event.
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 39) {
ball1X += 10;
}else if (key == 37) {
ball1X -= 10;
}else if (key == 40) {
ball1Y += 10;
}else if (key == 38) {
ball1Y -= 10;
}
if (ball1X < 12.5) {
ball1X += 400;
}else if (ball1X > 400-12.5) {
ball1X -= 400;
}
}
Other problems.
Use requestAnimationFrame for animations not setInterval
Key event listeners should only record the keyboard state as they have nothing to do with the game and dont know what to do with the keys pressed. The game code should use the keyboard state and its own current state to work out what to do with each key
Use addEventListener add events as directly setting event can be overwritten
Encapsulate your game inside a function so that all the variables and functions are isolated from the global names space and you can easily insert the game into any page.
Use objects to group properties and function together. Eg you had ballX, ballY and most like will add other properties each will have a ball prefix. By creating an object named ball and adding properties like x,y you can get access to the balls x, y with via a reference ball.x, ball.y or var b = ball; b.x += 1;`. Once an object has been defined you can make many copies easily.
Change the key handler to hold the key state of only the keys you are interested in. You only want to know if the key is down so listen to key up and down setting a flag to true when a key is down.
And other stuff
Rewrite
A quick rewrite showing a better way to implement what you had. It is a recommendation only. It is a little longer than you had it and is not the only way, but if you write like this it will be easier as the game develops.
See comments for the reasons and what does what.
// create onload event handler as a function and encapsulate all variables and functions to key global name space clean
function start(){
// create canvas and context
const canvas = document.getElementById("snakeCanvas");
const ctx = canvas.getContext("2d"); // formaly canvasContext;
// get the size as we use that a lot
const width = canvas.width;
const height = canvas.height;
requestAnimationFrame(mainLoop); // will call mainloop after this function (start) has run
// create an object to hold all related properties and
// functions for the ball
const ball = { // position ball in center
x : width / 2 | 0, // the or zero ( | 0) rounds down to nearest integer
y : height / 2 | 0,
size : 10,
speed : 10,
draw() { // function to draw the ball
ctx.fillStyle = 'black';
ctx.fillRect(this.x - this.size / 2,this.y - this.size / 2, this.size, this.size);
},
update() { // moves the ball
if (keys.up === true) { this.y -= this.speed }
if (keys.down === true) { this.y += this.speed }
if (keys.left === true) { this.x -= this.speed }
if (keys.right === true) { this.x += this.speed }
// get half size
const hSize = this.size / 2;
// check for edges and move to other side of canvas
if(this.x + hSize < 0) { this.x += width }
if(this.x - hSize > width) { this.x -= width }
if(this.y + hSize < 0) { this.y += height }
if(this.y - hSize > height) { this.y -= height }
},
}
// the background function clears and displays the background
function background(){
ctx.fillStyle = 'green';
ctx.fillRect(0,0,width,height);
}
// Object to hold the current keyboard state
const keys = {
up : false,
down : false,
left : false,
right : false,
map : new Map([ // use a Map to find keys
[39,"right"], // key code and string name of keys.name
[37,"left"],
[40,"down"],
[38,"up"],
])
}
// the key event listener
function keyEvents(event){
// get key code as a string
const keyCode = event.keyCode ? event.keyCode : event.which;
// get if avalible the key name from the map
const key = keys.map.get(keyCode);
// if a key is mapped set its state
if(key){
keys[key] = event.type === "keydown";
event.preventDefault(); // pervent default action
}
}
// listent to the keyboard events and set the keyboard state
["keydown","keyup"].forEach(eventName => addEventListener(eventName, keyEvents));
// for the stackoverflow snippet we need to get focus to
// hear any of the key events
focus();
function mainLoop(time){ // time is automatic and in ms (1/1000th second)
background(); // call the background function that clears and displays the background
// update and draw the ball object
ball.update();
ball.draw();
requestAnimationFrame(mainLoop); // request next frame in 1/60th second
}
}
// when loaded start the game
addEventListener("load", start);
<canvas id="snakeCanvas" width="400" height="400">

Click coordinates on canvas no longer match mouse after keydown simulated click

I’m using the keydown event to simulate clicks on a canvas. The click coordinates I’m using are window.innerWidth / 2 for x and 100 for y, which lie within the canvas. Then the click coordinates relative to the canvas are the red shaded area’s x-position + 1 and y-position + 1. This is the case as long as the keyDown variable is set to true on the keydown event. Otherwise, it’ll be the mouse click coordinates minus the canvas offsets. Therefore, an alert should say that the click was inside the shaded area every time I press the spacebar and only then.
The problem is that if I use the mouse to click an area after using the spacebar, the alert will keep showing the same coordinates as if I used the spacebar again. If I use the mouse after page load and before my first spacebar use, the alert will show the correct coordinates.
In other words, if I mouse-clicked (40, 39) and (170, 173), alerts will tell me that those areas were inside and outside the shaded area respectively. If I used the spacebar to simulate a chosen click at (26, 21) and then use the mouse again, the alert will keep giving me (26, 21). How I fix that?
var canvas = document.getElementsByTagName('canvas')[0],
ctx = canvas.getContext('2d'),
keyDown = false,
areaX = 25,
areaY = 20,
areaW = 100,
areaH = 100,
event = "ontouchstart" in document.documentElement ? "touchstart" : "click";
// shaded area
ctx.fillStyle = "rgb(192,0,0)";
ctx.fillRect(areaX, areaY, areaW, areaH);
function userAction(e, x, y, w, h, isKey) {
var cnv = document.getElementsByTagName('canvas')[0],
clickX = e.pageX - cnv.offsetLeft,
clickY = e.pageY - cnv.offsetTop;
if (isKey == true) {
// simulate click somwhere in area
clickX = x + 1;
clickY = y + 1;
}
if (clickX > x && clickX < x + w && clickY > y && clickY < y + h) {
alert("Inside shaded area at (" + clickX + ", " + clickY + ")");
} else {
alert("Ouside shaded area at (" + clickX + ", " + clickY + ")");
}
}
/* Click/touch function */
canvas.addEventListener(event, function(e){
userAction(e, areaX, areaY, areaW, areaH, keyDown);
});
/* Keyboard functions */
function clickByKbd(e, x, y) {
var key = e.keyCode;
if (key == 32) {
document.elementFromPoint(x, y).click();
return false;
}
}
document.documentElement.addEventListener("keydown", function(e){
keyDown = true;
clickByKbd(e, window.innerWidth / 2, 100);
});
document.documentElement.addEventListener("keyup", function(e){
keyDown = false;
});
body {
margin:0;
}
canvas {
display: block;
margin: auto;
outline: 1px solid #aaa;
}
<canvas width="200" height="200"></canvas>
The problem is that once you use the key, which changes keyDown to true, nothing ever sets it back to false.
If you put a trace in your keyup function, it never fires (you were probably hoping that would reset the var...it doesn't).
If you want to keep this code as is and use a minimal fix, do this:
document.documentElement.addEventListener("keydown", function(e){
keyDown = true;
clickByKbd(e, window.innerWidth / 2, 100);
keyDown = false; // reset after firing the event.
});
Note that now you can remove your keyup handler.

Canvas disappearing on event listener

I am trying to create a rect that moves on keypress for a pong game and when I press the key the left rect disappears..
Any ideas how to fix the problem? It is really important..
The code is written in vanilla javascript so please don't write jQuery..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong</title>
<script type="text/javascript">
var x = 100;
var y = 100;
var xmoveFirst = 720;
var ymoveFirst = 0;
var xmoveSecond = 30 ;
var ymoveSecond = 0;
function canvas() {
var can = document.getElementById('theCanvas');
can.style.backgroundColor = "black";
var ctx = can.getContext('2d');
//first player
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
//second player
ctx.fillStyle = 'white';
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
//first player move
function moveFirst(eFirst) {
ctx.clearRect(0,0,750,750); //clear rects
if (eFirst.keyCode == 40) {
ymoveFirst+=25;
console.log("first,"+ymoveFirst);
}
else if (eFirst.keyCode == 38) {
ymoveFirst-=25;
console.log("first,"+ymoveFirst);
}
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
}
var first = document.onkeydown = moveFirst;
//second player move
function moveSecond(eSecond) {
ctx.clearRect(0,0,750,750);
if (eSecond.keyCode == 83) {
ymoveSecond+=25;
console.log("second,"+ymoveSecond);
}
else if (eSecond.keyCode == 87) {
ymoveSecond-=25;
}
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
console.log("second,"+ymoveSecond)
}
var second = document.onkeydown = moveSecond;
}
83,87
</script>
</head>
<body onload="canvas()">
<canvas id="theCanvas" width="750" height="750"></canvas>
</body>
</html>
This line: can.width=can.width; resets the canvas width.
When you change the canvas size (width or height), you clear the canvas (making everything black). After this line, you are only redrawing the rightmost paddle, so the left one remains missing.
You'll need to redraw the leftmost paddle as well if you want it to come back. Here is the modified moveRight() function:
function moveRight(eFirst) {
if (eFirst.keyCode==40) {
ymoveFirst+=25;
console.log(ymoveFirst);
}
else if (eFirst.keyCode==38) {
ymoveFirst-=25;
console.log(ymoveFirst);
}
can.width=can.width;
ctx.fillStyle="white";
// Redraw BOTH paddles
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
}
Also, replace
document.onkeydown = moveFirst; and document.onkeydown = moveSecond;
with
document.addEventListener("keydown", moveFirst);, and document.addEventListener("keydown", moveSecond);
Currently, you are overwritting the first listener with document.onkeydown = moveSecond;. By using addEventListener, you don't overwrite the ones that already exist.

Trigger an event to call a function that's inside of a closure

I'm working on a project based on a nice little sample canvas drawing app someone else on the project downloaded and modified. We need to allow the user to click a button elsewhere on the page (not part of the canvas), and have it run a function that came with the sample app. However, the function is inside of a closure. Since I can't call the function directly (right? the closure prevents this? I don't often work with closures), I thought I'd be able to accomplish this by triggering a mouse event at the location the user would click to accomplish the same thing. It's not working, and I don't know why not.
I posted a greatly simplified version at this fiddle. Simple HTML code:
<div id="canvasDiv"></div>
<div id="buttonDiv">
<button>why can't I send a click to the canvas?</button>
</div>
And the simplified version of the downloaded sample app, plus my attempt to use jQuery's .trigger method to trigger the event:
var WM = {};
WM.drawingApp = function(options) {
"use strict";
var canvas, context,
// Add mouse and touch event listeners to the canvas
createUserEvents = function() {
var getElementPos = function(element) {
// straight-forward stuff removed for brevity's sake
return pos;
};
var press = function(e) {
// Mouse down location
var sizeHotspotStartX, toolIndex,
mouseX = (e.changedTouches ? e.changedTouches[0].pageX : e.pageX),
mouseY = (e.changedTouches ? e.changedTouches[0].pageY : e.pageY);
var elementPos = getElementPos(document.getElementById(options.canvasElementId || 'canvasDiv'));
mouseX -= elementPos.x;
mouseY -= elementPos.y;
announce(mouseX, mouseY);
};
var announce = function(x,y) { alert('press at: ' + x + ', ' + y); }
// Add mouse event listeners to canvas element
canvas.addEventListener("mousedown", press, false);
},
// Creates a canvas element, etc
init = function() {
// Create the canvas
canvas = document.createElement('canvas');
canvas.setAttribute('width', 100);
canvas.setAttribute('height', 100);
canvas.setAttribute('id', 'canvas');
document.getElementById(options.canvasElementId || 'canvasDiv').appendChild(canvas);
context = canvas.getContext("2d"); // Grab the 2d canvas context
createUserEvents();
};
init();
return {};
};
jQuery(document).ready(function() {
jQuery('#buttonDiv').on('click', 'button', function() {
var down = jQuery.Event("mousedown", {
pageX: 50,
pageY: 50
});
jQuery('#canvasDiv canvas').trigger(down);
});
});
As you can see by running the fiddle, if you click inside the box, you get an alert announcing where you clicked. But if you click the button, you don't get an alert. While writing this question, it occurred to me that maybe jQuery's .trigger method isn't a sufficient way to send the click. Its documentation page specifically says that .trigger "does not perfectly replicate a naturally-occurring event". We're open to solutions that don't involve jQuery.
You can define a variable var press; outside of WM, inside of WM, remove var before press and set press = function() {}. You should then be able to call press(down) at click of button
var press;
press = function(e) {
console.log(e);
// Mouse down location
var sizeHotspotStartX, toolIndex,
mouseX = (e.changedTouches ? e.changedTouches[0].pageX : e.pageX),
mouseY = (e.changedTouches ? e.changedTouches[0].pageY : e.pageY);
var elementPos = getElementPos(
document.getElementById(options.canvasElementId
|| 'canvasDiv')
);
mouseX -= elementPos.x;
mouseY -= elementPos.y;
announce(mouseX, mouseY);
};
jQuery(document).ready(function() {
jQuery('#buttonDiv').on('click', 'button', function() {
var down = jQuery.Event("mousedown", {
pageX: 50,
pageY: 50
});
press(down); // call `press` at `button` click
//jQuery('#canvasDiv canvas').trigger(down);
});
});
// based on http://www.williammalone.com/projects/html5-canvas-javascript-drawing-app-with-bucket-tool/
var press;
var WM = {};
WM.drawingApp = function(options) {
"use strict";
var canvas, context,
// Add mouse and touch event listeners to the canvas
createUserEvents = function() {
var getElementPos = function(element) {
var parentOffset, pos;
if (!element) {
pos = {
x: 0,
y: 0
};
} else {
pos = {
x: element.offsetLeft,
y: element.offsetTop
};
if (element.offsetParent) {
parentOffset = getElementPos(element.offsetParent);
pos.x += parentOffset.x;
pos.y += parentOffset.y;
}
}
return pos;
};
press = function(e) {
console.log(e)
// Mouse down location
var sizeHotspotStartX, toolIndex,
mouseX = (e.changedTouches ? e.changedTouches[0].pageX : e.pageX),
mouseY = (e.changedTouches ? e.changedTouches[0].pageY : e.pageY);
var elementPos = getElementPos(document.getElementById(options.canvasElementId || 'canvasDiv'));
mouseX -= elementPos.x;
mouseY -= elementPos.y;
announce(mouseX, mouseY);
};
var announce = function(x,y) { alert('press at: ' + x + ', ' + y); }
// Add mouse event listeners to canvas element
canvas.addEventListener("mousedown", press, false);
},
// Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
init = function() {
// Create the canvas (Neccessary for IE because it doesn't know what a canvas element is)
canvas = document.createElement('canvas');
canvas.setAttribute('width', 100);
canvas.setAttribute('height', 100);
canvas.setAttribute('id', 'canvas');
document.getElementById(options.canvasElementId || 'canvasDiv').appendChild(canvas);
context = canvas.getContext("2d"); // Grab the 2d canvas context
createUserEvents();
};
init();
return {};
};
jQuery(document).ready(function() {
jQuery('#buttonDiv').on('click', 'button', function() {
var down = jQuery.Event("mousedown", {
pageX: 50,
pageY: 50
});
press(down)
//jQuery('#canvasDiv canvas').trigger(down);
});
});
var drawingApp = WM.drawingApp({
canvasElementId: "canvasDiv"
});
#canvasDiv canvas {
border: solid black 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="canvasDiv"></div>
<div id="buttonDiv">
<button>why can't I send a click to the canvas?</button>
</div>
jsfiddle https://jsfiddle.net/gkvdha3h/5/

Drag and drop on the canvas - a couple of queries relating to functions

I came across the following very simple code for dragging a square around using javascript. It is drawn on the html5 canvas. Despite being very simple it has certainly exposed some gaps in my pretty flakey javascript knowledge. I am generally ok with the idea of drag and drop (i.e. start drag on mouse click, stop drag on mouse release) but my questions are as follows:
(1) I cannot see where the variable e is defined, yet it is used all the time.
(2) In the init funciton at the bottom, an onmousedown listener seems to be attached to the canvas. However it equals the function myDown, but myDown doesn't have parentheses after it. So the myDown function is not actually going to be exectuted. So what is it doing instead?
Thanks in advance. I have tried to research this myself but haven't had any success yet.
Matt
<html>
<head>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="400" height="300">
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#444444";
rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
</script>
</section>
</body>
</html>
You should really learn basic of the js language first.
1) e is param that is passed to functions. Callbacks receives one param: event object. So e stands for event.
2) myDown is not suppose to be executed when it is attached to onmousedown listener.
it is function object that is called everytime user clicks on canvas. It is callback.
e is the event variable which you get from onmousedown and onmouseup events. since you are attaching the mouse events with the canvas, so here e contains some information about mouse positions.
myDown is directly assigned to onmousedown which means that all the code of myDown function shall be assigned to onmousedown. If you add parenthesis after myDown then it would mean that you are assigning the response of myDown function to onmousedown event.
the other way of writing those events is like following
canvas.onmousedown = function(e)
{
myDown(e);
};
canvas.onmouseup = function(e)
{
myUp(e);
};
(1) I cannot see where the variable e is defined, yet it is used all the time.
You may know that a function is a set of instructions with input and output. They get their input through parameters and their output is what they return.
Now, the parameters they get are available in their body. This is why the e they get can be used inside.
(2) In the init funciton at the bottom, an onmousedown listener seems to be attached to the canvas. However it equals the function myDown, but myDown doesn't have parentheses after it. So the myDown function is not actually going to be exectuted. So what is it doing instead?
Function is a special object in javascript, with an extra internal property [[Call]]. When you type the function name alone, you're talking about the function itself. And as it is a first-class object it can be assigned to a variable, passed as an argument, returned from other functions, etc.
When you type the function name with parenthesize after it you execute the code in the function body by the [[Call]] internal property.

Categories

Resources