Why am I able to run and build Javascript without semicolons? [duplicate] - javascript

This question already has answers here:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Closed 3 years ago.
In an online course, I'm following on Udemy, the instructor is putting semicolons after lines and says they are needed. I forgot to put some because I'm just getting off of Python and the code still ran.
var firstName = 'John';
console.log(firstName);
var lastName = 'Smith';
var age = 28;
console.log(lastName)
console.log(age)
When I right click on the browser and click on console the first, last name and age are displayed. Can anyone help explain why its working without the semicolons? I'm assuming they are needed when writing Javascript.

This is because Javascript parser will automatically insert semicolon for you in the following situations:
Copypasta from Flavio Copes' Let’s talk about semicolons in JavaScript
when the next line starts with code that breaks the current one (code can spawn on multiple lines)
when the next line starts with a }, closing the current block
when the end of the source code file is reached
when there is a return statement on its own line
when there is a break statement on its own line
when there is a throw statement on its own line
when there is a continue statement on its own line
For best practices, semicolons should be manually inserted.

JavaScript doesn't actually need semicolons. Unless you're writing more than one statement on the same line (please don't, with the exception of for loops)

Related

JS variable inside of PHP inside of JS inside of PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
Having a bad day. This one has stumped me all morning. All the solutions I've found have stopped one step short of where I need to go.
I have a legacy PHP/JS app that I'm working on. Rather than trying to explain it, I'll just show what I need to do.
<?php
$phpDate_1 = new Date($someDate);
$phpDate_2 = new Date($someOtherDate);
//...There are a bunch of these
$phpDate_n = new Date($endOfTime);
<script language="javascript">
function myFunction() {
var line = aUserSelection; //an int from user which tells me what date to use
//Next line is the problem. I'm trying to pull the month from the appropriate PHP date into the JS variable.
var theMonth = "<?php echo $phpDate_" + line + "->getMonth();?>";
}
</script>
?>
I must have tried 20-30 combinations of single and double quotes, escapes, dots, pluses, and so on, but I keep getting errors over the "line" part. Unexpected character, encapsed strings, etc.
Hoping someone can point me in the right direction because my brain is fried at this point. Answers in pure JS and PHP only please because that's how the app is built. Thanks.
You need to close your php (?>) before outputting the javascript to fix the syntax error that you got.
However, with that said, you are trying to incorporate the javascript line variable into the variable name for $phpDate, to generate something like $phpDate_1.
If you don't want to go with an AJAX solution, your best bet would be to output each line's date into a javascript array. This is strongly discouraged, but if this is a legacy application that you cannot make many changes to, this might be your only option.

<script> Invalid comment formatting? [duplicate]

This question already has an answer here:
Does HTML comment <!-- act as a single-line comment in JavaScript, and why?
(1 answer)
Closed 7 years ago.
I have taken on a project that someone else has worked on and I am running into a bunch of script blocks formatted like this:
<script>
<!--
$('...').live('change', function() {
if (...) {
$('...').hide();
$('...').show();
} else {
$('...').show();
$('...').hide();
}
});
//-->
</script>
They are not even the correct comment format for JavaScript.
The code still works but should I worry that this might break in the long term if I start adding to it?
Is this just blatantly wrong and should I remove all the invalid comments?
To formalize my comment.
Back in the day not all browsers supported JavaScript. To make the JS disappear it would be wrapped in an HTML comment and the browser would effectively ignore it.
This hasn't been relevant for some time now and it can be safely deleted.
It can also be left in without harm, but ew.
By way of example, this question from 2009 asks the question re: relevancy, not what it actually is.
This also means I'm old :(

Why js can't understand string '</script>'? [duplicate]

This question already has answers here:
javascript variable that contains </script>
(3 answers)
Closed 8 years ago.
I have a simple javascript (jsFiddle):
alert('</script>');
Browser fails to understand it.
This is console output:
Uncaught SyntaxError: Unexpected token ILLEGAL
But this script works (jsFiddle):
alert('</scriptt>');//shows alert text '</scriptt>'
Is it some kind of browser bug or normal ECMAScript behaviour?
(browser is Chrome)
Because it is considered as:
<script>
alert('
</script>
');
which is a SyntaxError
You can use
alert( '<\/script>\n');
The HTML parser does not understand JavaScript und thus looks for something which closes the tag which is </script>. If you need '</script>' as string in JavaScript simply use '</s'+'cript>'.
JavaScript isself does not have such a problem, using var x = '</script>'; in nodejs is no problem. The HTML parser is.
This is Javascript embedded in HTML script tags, right?
Then the HTML parser terminates your script in the middle.
Put the Javascript into its own file or break up the string literal. Maybe a CDATA section also works.

Why does this JavaScript statement begin with a ; [duplicate]

This question already has answers here:
What does the leading semicolon in JavaScript libraries do?
(6 answers)
Closed 9 years ago.
It's looks extraneous, but it must do something.
ref: https://github.com/quirkey/sammy/blob/master/examples/hello_world/index.html
<script type="text/javascript" charset="utf-8">
;(function($) {
//snip
});
$(function() {
//snip
});
})(jQuery);
</script>
This is to make sure previously loaded code that could have not been terminated with a semicolon gets terminated properly, otherwise it would result in an error. You could say it makes the code more tolerant to other people's bugs.
Update: I tested this out and at least in current Chrome and Firefox it makes no difference whether a previous statement is still open, so the semicolon has no effect on that. Idea: that might still be a problem with very old browsers, but I it is just an idea I didn't verify.

omiting number sign using regex in java script not working [duplicate]

This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
I have written a simple code in a .js file (in Zend framework, but I dont think it matters)
var location = "localhost:8080/mymodule/id/1#";
location.replace(/\#/g, "");
alert(location.valueOf());
return;
but I dont know why I can not see the result I want.
I get my page url and want to omit all number signs appears in it. but the code above does nothing.
please help
location is a bad name to use for a variable since it collides with the window.location variable used for the actual browser page location.
If you change location to loc in your above code, and then also add loc = in front of the loc.replace() call (since replace() doesn't modify the input, but instead returns the new version), your code works.
replace will not change the value of the original string, you need to assign the result to a new variable -
var newString = location.replace(/#/g, "");
alert(newString);
Demo - http://jsfiddle.net/5H5uZ/
It can be done in one line. This is the result you look for?
alert("localhost:8080/mymodule/id/1#".replace(/#/g,''));
//=> alerts 'localhost:8080/mymodule/id/1'

Categories