I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
You forgot to return a value, so the return-value is undefined.
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
return 'Hello ' + first + second + '!';
}
console.log(greet('Gemma'));
The console will print the result of evaluating an expression. You can notice if you set
let name = 'john'
it will print undefined in the very next line.
That is also happening here. First it is printing your value, then it print undefined.
Your function is working fine - you just need to invoke it and feed its argument with a name...
[for the result look in the console]
var greet = function(name) {
let first = String(name.charAt(0).toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
;
greet("henky");
Related
I've been watching a javascript tutorial to refresh my knowledge of it.
I just need some guidance on why he decided to use this code "style"
Basically, there's a variable named result with an empty string ("") and I'm not so sure why he used (result += ...) when he can also use (result = ...) where it showed the same output when I tried.
function mySentence(myName, myVerb){
var result = "";
result += myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
vs
function mySentence(myName, myVerb){
var result = "";
result = myName + " " + myVerb + " towards the tree.";
return result;
}
console.log(mySentence("Dale", "walked"));
Link of video: https://youtu.be/PkZNo7MFNFg
36:28:00 : Word Blanks
The only reason I can think of for having it there is that the author wanted to be able to rearrange a series of statements after the initial declaration that all used += without having to worry about which was the first statement originally. E.g.:
var result = "";
result += "something";
result += "another thing";
result += "yet another thing";
...where they may want later to swap things around:
var result = "";
result += "another thing";
result += "something";
result += "yet another thing";
The variable result is set to "", an empty string in the beginning.
When you do result= the variable will be replaced with the new value.
But when you do result+= the variable does not get replaced. It will be added with the value that already exists.
For example, in your code, if the variable is set to some value in the beginning, like result="The answer is: ", then the two styles would yield different results. The result= style will return Dale walked towards the tree.. And the result+= will return The answer is: Dale walked towards the tree.
How can I get this working, I am not sure what I am doing wrong here.
let args = message.content.substring(PREFIX.length).split(" ");
const a = args;
const items = a.slice(a.indexOf('{') + 1, a.lastIndexOf('}')).split('}{')
switch(args[0]) {
case 'status':
message.channel.send("**Current Status:**");
con.query("SELECT * FROM games", function(err, result, fields) {
if(err) throw err;
Object.keys(result).forEach(function(key) {
var row = result[key];
message.channel.send('**' + row.name + '**' + ' - ' + '(' + row.description + ')' + ' - ' + '**' + row.status + '**');
});
});
break;
case 'add':
let name = items[1];
let desc = items[2];
let status = items[3];
console.log(items);
break;
I am trying to split the !ADD commands arguments by {} so this system knows that every other string inside of {} is the next command
!add {this is a argument}{another argument}{another argument sitting here}
I think the issue is that you are splitting the message to parse out the initial command (add), but not joining it back together before doing the next split. I think you want to change the second line to:
const a = args.slice(1).join(' ');
That should make the items array ['this is a argument', 'another argument', 'another argument sitting here']
When you access the items array, make sure you are using the correct indices as well. In this example there are only 3 items, so valid indexes would be (0, 1, 2). (In your code you are accessing 3)
A light regexp-using approach could be:
let line="!add {this is a argument}{another argument}{another argument sitting here}"
let [command,argumentlist]=line.match(/!([^\s]+)\s+\{(.*)\}/).splice(1);
let arguments=argumentlist.split("}{");
console.log(command);
console.log(arguments);
The match() thing strips the ! from the beginning and the outermost {} pair, and then the split() is the same as it was in your code.
I have a function that takes 2 inputs, the variable name as a string and the variable itself - it prints both via console.
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis("variable1", variable1) ;
I want to be able to use it as logthis(variable1); and get the same result.
How can I reference the variable name (as a string) and not its contents?
eg, console.log(input2.name) will not work
Something like the C+ equivalent of "nameOf(variable1)"
var variable1 = ["entry1","entry2"];
function logthis(input1, input2){
console.log(input1+ "\n " + input2)
}
logthis('variable1', variable1) ;
You are sending the reference. Pass first argument as string.
Try to get your input from the table first
function logthis(inputTable){
var input1 = inputTable[0];
var input2 = inputTable[1];
console.log(input1+ "\n " + input2) // will display "entry1 \n entry2 "
}
var table1 = ["entry1","entry2"];
logthis(table1);
I'm fairly new to Javascript, and am confused on something. Why can't the command "println("..."); be called as a variable such as: var num = println("...");. I could be wrong, and if you are able to, I'd be happy to know how. But after some testing it seems like I can't. My test code is:
function start() {
var SENTINEL = "1 1";
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = println(rollOne + rollTwo);
if(num == SENTINEL) {
println("You did it");
}
}
All it's supposed to do is give to random numbers in a # # form and, if it sees that the numbers are 1,1, it will give a message. It wont give the message and can't seem to view the variable "num" as an actual variable. But when I change the variable num to simply asking the user for a number:
function start() {
var SENTINEL = -1;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = readInt("Enter number");
if(num == SENTINEL) {
println("You did it");
}
}
And type in -1, it triggers the sentinel, thus promptly displaying the message. This is a really roundabout way to ask a simple question but I hope I can get some help. Thank you :)
Why can't the command "println("..."); be called as a variable such as: var num = println("...");
[...] It wont give the message and can't seem to view the variable
If the value returned is unusable, it is most likely undefined; i.e. The function println doesn't explicitly return anything.
In your case, you could try something like this:
var printInt = function(num) { println(num); return num; }
Note, println isn't part of the standard JavaScript language. For modern web browsers, it can be adapted to use (console.log(...)).
var printInt = function(num) { console.log(num); return num; }
And then to adapt to your code:
var num = printInt(rollOne + rollTwo);
But this still won't validate because you're comparing against "1 1" whereas your logic will return 2. JavaScript (as well as many other languages) implicitly uses addition when supplied with two numbers, but concatenation when supplied with at least one string.
var SENTINEL = "1 1"; // <---- String!
var SENTINEL = -1; // <---- Number!
So you should consider something like this instead (renamed accordingly):
var printRolls = function(text) { println(text); return text; }
var rolls = printRolls(rollOne + " " + rollTwo);
if(rolls == SENTINEL) {
println("You did it");
}
Or to simplify it a bit:
if(printRolls(rollOne + " " + rollTwo) == SENTINEL)
println("You did it");
It is possible that println doesn't return the string that is passed into. In that case, you can use
if (SENTINEL === rollOne + " " + rollTwo)
to format the string and properly test equality.
In JavaScript it is possible to assign the return value from any function to a variable similar to how you've done it:
var anyVariable = anyFunction();
But, some functions return the value undefined. Or they return a number, or an array, or...whatever.
I imagine your println() function prints the value you pass to it somewhere (on the screen? to the console?) and then returns undefined. Or if it is returning the printed value it is in a format different to what you have used in your SENTINEL variable. So then when you try to compare that with SENTINEL it won't be equal.
To fix your original function, assign the sum of the rolls to a variable, then print and test that:
function start() {
var SENTINEL = 2;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = rollOne + rollTwo;
println(num);
if(num == SENTINEL) {
println("You did it");
}
}
EDIT: if you want the println() to display a string like "1 1" or "3 5" to show what each of the two rolls were then do this:
println(rollOne + " " + rollTwo);
That is, create a new string that is the result of concatenating rollOne's value with a single space and then rollTwo's value.
Can anyone tell me why this is not working?
var fieldsValid = {
registerUserName: false,
registerEmail: false,
registerPassword: false,
registerConfirmPassword: false
};
function showState () {
var str = "<p>registerUserName: " + fieldsValid[registerEmail] + "</p>" ;
document.getElementById('showstate').innerHTML = str;
}
showState();
There is no output into my div.
Use quotes around the property name because otherwise, registerEmail is treated as a variable containing the property name, not a property name:
var str = "<p>registerUserName: " + fieldsValid['registerEmail'] + "</p>" ;
Or use the . syntax without quotes:
var str = "<p>registerUserName: " + fieldsValid.registerEmail + "</p>" ;
MDN Working With Objects is a good resource, relevant to this.
For future debugging, observe the console (F12) in your browser.
Let's say you have someObject.
someObject[johndoe] Returns the item in someObject that has johndoe's value (since here it is a variable) as index.